在 for 循环内等待承诺

2023-12-06

let currentProduct;

for (let i = 0; i < products.length; i++) { 
    currentProduct = products[i];

    subscription.getAll(products[i]._id)
        .then((subs) => {
            update(subs, currentProduct);
        });
}

我正在使用蓝鸟,方法getAll and update回报承诺。我怎么说“等到两个承诺返回,然后更新 currentProduct 值”?我对 JS 还很陌生...


如果您可以使用,这将很简单async/await:

// Make sure that this code 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 code 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:
    /*
    const subs = await subscription.getAll(products[i]._id);
    await update(subs, currentProduct);
    */
}

或者,如果您只能使用简单的承诺,则可以循环遍历所有产品,并将每个承诺放入.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 code 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 code 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直到前面的每个函数依次解决(这就是您想要的)后,函数才会运行。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 for 循环内等待承诺 的相关文章

随机推荐

  • CallKit 中的 CXStartCallAction isVideo 属性和本机视频按钮如何使用?

    我试图弄清楚当用户点击本机 iOS 通话屏幕中的视频按钮时会发生什么 我已经浏览了一些教程并查看了代码 它似乎不是委托方法或任何东西 CXStartCallAction有一个属性 var isVideo Bool 但我似乎无法弄清楚它是如何
  • 将变量从 bash 传递到可执行文件(使用 stdin 读取参数)

    我有以下内容test cppC 程序 include
  • XSLT 1.0 中的条件

    我有一个 XSLT 1 0 2 0 不是一个选项 样式表 它生成 XHTML 它可以根据参数生成完整的 XHTML 有效的文件或只是 div div 片段 旨在用于 包含在网页中 我的问题是在这两个中生成不同的 XML 声明 案例 对于独立
  • 通过比较 2 个相邻元素对数组进行分组

    我有一个对象数组 我想根据两个相邻元素的属性之间的差异对它们进行分组 该数组已按该属性排序 例如 原始数组 array a b c d e and a attribute 1 b attribute 3 c attribute 6 d at
  • 异步可插拔协议

    Using this作为参考 我正在尝试创建一个异步可插入协议 该协议仅暂时可供我的应用程序使用 并且未在系统范围内注册 我在用着CoInternetGetSession然后打电话RegisterNameSpace去做吧 然而 当我打电话给
  • 异步编程是否意味着多线程?

    让我们来谈谈 JavaScript 代码setInterval方法每个2 sec 我也有一个onblur某些控件的动画事件 在这种情况下onblur发生 动画 我可能会得到setInterval功能 Question 异步编程是否意味着多线
  • Nothing 等于 Default 吗?

    当我在 VB NET 中将变量设置为空时会发生什么 真的没有什么等于默认吗 还是我在这里遗漏了一些东西 如果它是值类型 如 Integer Double 等 则将变量设置为 Nothing 会将其设置为默认值 如果它是引用类型 它实际上会被
  • Spring Boot:热插拔不起作用

    我正在使用 Spring Boot 1 3 2 和 gradle 插件 在我的多部分项目中 HTML JS CSS 文件的热交换 重新加载不起作用 resources wro groovy application yml templates
  • Cosmos DB - 删除文档

    如何从 Cosmos DB 中删除单个记录 我可以使用 SQL 语法进行选择 SELECT FROM collection1 WHERE collection1 ts gt 0 果然所有文档 类似于行 都被返回 但是 当我尝试删除时这不起作
  • 如何配置代理设置以便 Eclipse 可以下载新插件?

    我正在使用 Eclipse 3 7 在 Web 代理后面的 Windows XP 环境中 我想安装Groovy 插件 on a 新解压的日食靛蓝 Eclipse Java EE Indigo M4 我添加了更新站点 to the Avail
  • 使用 lubridate 和 dplyr 将多列转换为日期

    我正在寻找一种简单的方法来将数据框中以 日期 开头的所有变量转换为日期lubridate dmy 它们目前是 dmy 格式的字符 我原以为 mutate if 或 mutate each 可以完成dplyr但我正在努力弄清楚如何做 您可以使
  • 在运行时更改一组特定车辆的传输信号强度

    我开始 大约一周以来 在 omnet 5 0 下使用静脉 4 4 我目前的任务是让车辆根据具体情况调整其传输范围 我确实阅读了很多像这样的问题 以及在其他主题 论坛中 ieee802 11p模块中的动态传输范围 车辆接收 RSU 范围外的信
  • 在R中绘制线段

    我有一些 x 和 y 坐标 我试图将它们绘制成线段 我从我认为应该有效的行为中得到了一些意想不到的行为 对于每个线段 都有一组起始坐标 x1 y1 和一组结束坐标 x2 y2 这是一个数据框 称为 df 如下所示 x1 y1 x2 y2 3
  • D3 csv 返回行

    这是来自d3csv API 文档 d3 csv path to file csv row function d return key d key value d value get function error rows console l
  • uwp:如何根据列表视图项的值更改其背景颜色?

    编辑 UWP 应用程序与 WPF 应用程序并非 100 相同 我有一个带有 ListView 的 uwp 应用程序 在 ListView 中 我使用带有测试类的 DataTemplate 它显示测试的名称和点 我想要完成的是一个触发器 检查
  • 如何使用 build.xml 在 java 代码中设置属性

    我是 Ant 的新手 任何帮助将不胜感激 我想做的是 当我调用 Ant 目标时 我正在执行以下操作 ant DSIMV3 1 true run tenantManagement 现在在 build xml 中 我有
  • Firestore查询仅包含集合的文档

    我有一个 firestore 集合 里面有一些文档 这些文档仅包含集合 不包含任何字段 因此 当我尝试获取根集合中的所有文档时 我得到的快照大小为零 有没有办法获取没有字段但里面有一些集合的文档 我的 Firestore 结构是 您还可以看
  • 如何从寄存器中提取值?

    我试图弄清楚如何从 ASM 指令中提取寄存器值并将其放入 C 中的变量中 例如 MOV DWORD PTR DS ESI EDI 假设EDI保存的值是一个int int Value EDI 取决于你的编译器 搜索 内联汇编 和您使用的编译器
  • 如何从 Windows Phone 上的前台应用程序发出 ScheduledTask 信号?

    我正在创建一个具有前台应用程序 当然 以及周期性任务和资源密集任务的应用程序 如果用户在运行时启动应用程序本身 我需要一种方法来关闭计划任务 我没有看到任何方法可以使用系统范围的互斥体来做到这一点 理想情况下 当后台任务启动时 将分离一个线
  • 在 for 循环内等待承诺

    let currentProduct for let i 0 i lt products length i currentProduct products i subscription getAll products i id then s