栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

等待promise for循环

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

等待promise for循环

如果可以使用

async
/,这将很简单
await

// Make sure that this pre is inside a function declared using// the `async` keyword.let currentProduct;for (let i = 0; i < products.length; i++) {     currentProduct = products[i];    // By using await, the pre will halt here until    // the promise resolves, then it will go to the    // next iteration...    await subscription.getAll(products[i]._id)        .then((subs) => { // Make sure to return your promise here... return update(subs, currentProduct);        });    // You could also avoid the .then by using two awaits:    }

或者,如果您只能使用简单的承诺,则可以遍历所有产品,并将每个承诺置于

.then
最后一个循环中。这样,仅当前一个问题解决时,它才会前进到下一个问题(即使它将首先迭代整个循环):

let currentProduct;let promiseChain = Promise.resolve();for (let i = 0; i < products.length; i++) {     currentProduct = products[i];    // Note that there is a scoping issue here, since    // none of the .then pre runs till the loop completes,    // you need to pass the current value of `currentProduct`    // into the chain manually, to avoid having its value    // changed before the .then pre accesses it.    const makeNextPromise = (currentProduct) => () => {        // Make sure to return your promise here.        return subscription.getAll(products[i]._id) .then((subs) => {     // Make sure to return your promise here.     return update(subs, currentProduct); });    }    // Note that we pass the value of `currentProduct` into the    // function to avoid it changing as the loop iterates.    promiseChain = promiseChain.then(makeNextPromise(currentProduct))}

在第二个代码段中,循环仅建立了整个链,但没有

.then
立即执行内部代码。您的
getAll
功能要等到之前的每个功能依次解决后才能运行。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/568998.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号