gpt4 book ai didi

javascript - 通过 promise 链向下传递变量

转载 作者:行者123 更新时间:2023-11-29 15:16:59 27 4
gpt4 key购买 nike

我对 promises 有点陌生,所以请原谅我缺乏知识。下面的代码突出显示了我想做的事情,但显然我做不到。

var token = "";
var id = "";
var cms = {
login: function () {
return request({
"method": "POST",
"uri": process.env.CMS_URL + "/cms/login",
"json": true,
"body": {
"email": "xxxxxxx",
"password": "xxxxx"
}
}).then(response => {
console.log("Successfully logged in to cms. Access token: " + response);
token = response;
}).catch(error => {
console.log("Couldn't get access token from cms");
});
},
createCollection: function (token) {
return request({
"method": "POST",
"uri": process.env.CMS_URL + "/cms/collection",
"json": true,
"headers": {
"X-Cms-Token": token
},
"body": {
"name": "Acceptance test collection",
"type": "manual"
}
}).then(response => {
console.log("Successfully created a collection.");
id = response.id;
}).catch(error => {
console.log("Collection already exists");
});
},
deleteCollection: function (token, id) {
return request({
"method": "DELETE",
"uri": process.env.CMS_URL + "/cms/collection" + id,
"json": true,
"headers": {
"X-Cms-Token": token
}
}).then(response => {
console.log("Successfully deleted collection.");
}).catch(error => {
console.log("No collection to delete");
console.log(error);
});
}
};
var createCollectionCms = function (token, id) {
return new Promise((resolve) => {
cms.login()
.then(zebedee.createCollection(token))
.then(zebedee.deleteCollection(token, id));
setTimeout(resolve, 6000);
});
}
createCollectionCms();

我需要运行每个函数并传入“token”和“id”。通过上面的方法,每个函数同时运行。我需要它们彼此执行但传递所需的变量。

基本上我需要登录,创建一个“集合”,然后删除“集合”。这是我正在设置的一些测试的一部分。

最佳答案

这是使用 async/await 来使用 Promises 的可读且看起来同步的替代方法(实际上仍然在底层使用 Promises)

// returns a Promise whose response is the token
const requestAccessToken = cmsUrl => request(/* request options with cmsUrl */)

// returns a Promise whose response is the collectionId
const createCollection = token => request(/* request options with token */)

// returns a Promise whose response is given by deleting the respective collection
const deleteCollection = collectionId => request(/* request options with collectionId */)

// create and execute an async function that puts all these functions together in a synchronous manner
const createThenDeleteCollection = async cmsUrl => {
try { // if at any time an error is thrown, the error is caught and logged
const token = await requestAccessToken(cmsUrl)
const collectionId = await createCollection(token)
const responseFromDeletingCollection = await deleteCollection(collectionId)
console.log(responseFromDeletingCollection)
} catch (err) {
console.error(err)
}
}
createThenDeleteCollection(process.env.CMS_URL)

使用此方法的一个警告是,如果您在浏览器中执行它,IE 不支持它,如果您在 Node 中执行,则至少需要使用 7.6 版

关于javascript - 通过 promise 链向下传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48173385/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com