简体   繁体   English

按顺序运行Q承诺并将值传递给下一个承诺

[英]Running Q promises sequentially and pass values to next promise

I simplified my problem to easily give an illustration. 我简化了我的问题,以方便举例说明。 I would like to implement the function sequential : 我想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;
}

Obviously, that loop will not guarantee that last_element and results will be up to date as another doSomething promise runs. 显然,该循环不能保证last_elementresults将是最新的,因为另一个doSomething承诺会运行。 Is there an ideal way to do this using q? 是否有使用q执行此操作的理想方法?

Not sure why you are using Q with nodejs unless the node version you are using is seriously old. 不知道为什么将Q与nodejs一起使用,除非所使用的节点版本非常老。

Also can't make sense of what it is your code is supposed to do but since you have a list you can either map it to promises and process everything in parallel or reduce the list and process everything in series (one after the other): 也无法理解代码应该执行的操作,但是由于有了列表,您可以将其映射到Promise并并行处理所有内容,也可以减少列表并按顺序处理所有内容(一个接一个):

 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) ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM