首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Bluebird Promises:链式promises的顺序异步执行,其中包含for循环

Bluebird Promises:链式promises的顺序异步执行,其中包含for循环
EN

Stack Overflow用户
提问于 2020-04-13 02:38:38
回答 1查看 30关注 0票数 0

为了避免回调地狱,我链接了几个(Bluebird Promise)指令,每个指令都运行一个异步的for循环。当for循环仍在运行时,链不再等待每个for循环完成,而是直接冲到显示“完成”的结尾处。如何更改我的for循环,以便promise链在执行下一个"then“部分之前”等待“每个循环完成?

代码语言:javascript
复制
return Object1.Asyncmethod1(param1)
  .then(function(result1) {

    var promiseFor = Promise.method(function(condition, action, value) {
      if (!condition(value)) return value;
      return action(value).then(promiseFor.bind(null, condition, action));
    });

    promiseFor(function(count) {
      return count < result1.length;
    }, function(count) {
      return Object.someOtherAsyncAction(someParam)
        .then(function(res) {
          return ++count;
        });
    }, 0)

  }).then(function(result2) {
    //another for loop just like the one above  
  }).then(function(result3) {
    console.log("DONE");
    res.json({
      result: result3
    });
  }).catch(function(err) {
    res.json({
      result: 'error:' + err
    });
  });
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-13 02:44:06

您不会退还promiseFor创建的Promise。至此,链断开了,.then(function(result2) {不会等待代码完成。您需要在promiseFor(function(count) {前面添加一个return

代码语言:javascript
复制
  .then(function(result1) {

    var promiseFor = Promise.method(function(condition, action, value) {
      if (!condition(value)) return value;
      return action(value).then(promiseFor.bind(null, condition, action));
    });

    return promiseFor(function(count) {
      return count < result1.length;
    }, function(count) {
      return Object.someOtherAsyncAction(someParam)
        .then(function(res) {
          return ++count;
        });
    }, 0)

  })
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61176371

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档