按顺序运行Q promises并将值传递给下一个promise

时间:2018-02-01 23:26:33

标签: javascript node.js asynchronous promise q

我简化了我的问题,轻松举例说明。我想实现函数sequential

var Q = require('q');

sequential = function(list) {
    last_element = 0;
    results = [];
    list.forEach(function(element) {
        doSomething(element, last_element).then(function (result) {
            results.push(result);
        });
    })
    return results;
}

doSomething = function(element, last_element) {
    var defer = Q.defer();
    some_result_from_api = "this is supposed to be an async operation"
    result = element * last_element * some_result_from_api;
    defer.resolve(result);
    return defer.promise;
}

显然,该循环不保证last_elementresults将在另一个doSomething承诺运行时保持最新状态。有没有理想的方法来使用q?

1 个答案:

答案 0 :(得分:0)

不确定为什么要将Q用于nodejs,除非您使用的节点版本严重旧版。

也无法理解你的代码应该做什么但是因为你有一个列表,你可以将它映射到promises并并行处理所有内容或者减少列表并处理所有系列(一个在另一个之后):



sequential = function(list) {
  //in parallel: 
  // return Promise.all(
  //   //last_element is 0 and never changes so I made it 0
  //   list.map(doSomething(element, 0))
  // );
  //serial; one after the other:
  return list.reduce(
    (p,item)=>
      p.then(
        results=>
          //last_element is 0 and never changes so I made it 0
          doSomething(item, 0)
          .then(
            result=>
              results.concat([result])
          )
      ),
      Promise.resolve([])
  );
}

doSomething = async function(element, last_element) {
  const some_result_from_api = await "this is supposed to be an async operation"
  return [element, last_element, some_result_from_api];
}
sequential([1,2,3])
.then(
  results=>
    console.log("Got results:",results)
);