如何在 javascript 承诺链中使用循环
How to use loop in javascript promises chain
我是 JS 的新手,无法将 promise 概念应用到我的用例中,我和其他人一样检查了 this SO,但无法为我的案例推导出解决方案。
我需要在循环内调用 promises 但只有在循环完成后才应该调用下一个 "then" 。这在 JS 中可行吗?
function startCooking(ingredients) {
Utility.startConnection()
.then(
function (connectionTime) {
for (let [key, plainVector] of ingredients) {
encryptIngredients(plainVector)
.then(
function (encryptedBinary) {
return Utility.cookDinner();
}
).then(
function (dinner) {
console.log(...);
}
);
}
}
).catch(
...
);
}
function encryptIngredients() {
return new Promise(...);
}
这就是它的大致工作方式。
如果此函数加密单一成分:
function encryptIngredient(ingredient) {
return new Promise(...);
}
然后这个函数加密成分列表:
function encryptIngredients(ingredients) {
// Note that 'shift' changes the array
const current = ingredients.shift();
return encryptIngredient(current).then( () => {
if (ingredients.length > 0) {
return encryptIngredients(ingredients);
}
});
}
这是最后一个函数的 async/await 版本。简单多了:
async function encryptIngredients(ingredients) {
for(const ingredient of ingredients) {
await encryptIngredient(ingredient);
}
}
我是 JS 的新手,无法将 promise 概念应用到我的用例中,我和其他人一样检查了 this SO,但无法为我的案例推导出解决方案。 我需要在循环内调用 promises 但只有在循环完成后才应该调用下一个 "then" 。这在 JS 中可行吗?
function startCooking(ingredients) {
Utility.startConnection()
.then(
function (connectionTime) {
for (let [key, plainVector] of ingredients) {
encryptIngredients(plainVector)
.then(
function (encryptedBinary) {
return Utility.cookDinner();
}
).then(
function (dinner) {
console.log(...);
}
);
}
}
).catch(
...
);
}
function encryptIngredients() {
return new Promise(...);
}
这就是它的大致工作方式。
如果此函数加密单一成分:
function encryptIngredient(ingredient) {
return new Promise(...);
}
然后这个函数加密成分列表:
function encryptIngredients(ingredients) {
// Note that 'shift' changes the array
const current = ingredients.shift();
return encryptIngredient(current).then( () => {
if (ingredients.length > 0) {
return encryptIngredients(ingredients);
}
});
}
这是最后一个函数的 async/await 版本。简单多了:
async function encryptIngredients(ingredients) {
for(const ingredient of ingredients) {
await encryptIngredient(ingredient);
}
}