Is there a pure Promise-based approach for mapping/concatenating collections?

后端 未结 1 1453
有刺的猬
有刺的猬 2020-12-17 10:58

async vs. Q generally

I\'m learning Node.js development, and trying to wrap my brain around strategies for managing asynchronous \"callback hell\". The two main s

相关标签:
1条回答
  • 2020-12-17 11:28

    Do I really need both?

    No. Mapping asynchronous iterators over a collection is quite simple with promises, but it requires two steps instead of one function call. First, the collection is mapped to an array of promises for the parallel iteration. Then, those promises are fed into Q.all to make one promise for the mapped collection. In contrast to async, the order of the result is guaranteed.

    var entries = […]; // some array of objects with "id" attributes
    
    var promises = entries.map(function(object) {
        return asyncPromiseReturingFunction(object);
    }); // the anonymous wrapper might be omitted
    return Q.all(promises);
    

    For concat, you would have to append a

    .then(function(results) {
         return Array.prototype.concat.apply([], results);
    });
    
    0 讨论(0)
提交回复
热议问题