繁体   English   中英

Node JS Promise.all 和 forEach

[英]Node JS Promise.all and forEach

我有一个类似数组的结构,它公开了异步方法。 异步方法调用返回数组结构,这些结构又会公开更多异步方法。 我正在创建另一个 JSON 对象来存储从这个结构获得的值,所以我需要小心跟踪回调中的引用。

我已经编写了一个蛮力解决方案,但我想学习一个更惯用或更干净的解决方案。

  1. 对于 n 级嵌套,该模式应该是可重复的。
  2. 我需要使用 promise.all 或一些类似的技术来确定何时解决封闭例程。
  3. 并非每个元素都必然涉及进行异步调用。 因此,在嵌套的 promise.all 中,我不能简单地根据索引对 JSON 数组元素进行分配。 尽管如此,我确实需要在嵌套的 forEach 中使用 promise.all 之类的东西,以确保在解析封闭例程之前已经进行了所有属性分配。
  4. 我正在使用 bluebird promise lib 但这不是必需的

这是一些部分代码 -

var jsonItems = [];

items.forEach(function(item){

  var jsonItem = {};
  jsonItem.name = item.name;
  item.getThings().then(function(things){
  // or Promise.all(allItemGetThingCalls, function(things){

    things.forEach(function(thing, index){

      jsonItems[index].thingName = thing.name;
      if(thing.type === 'file'){

        thing.getFile().then(function(file){ //or promise.all?

          jsonItems[index].filesize = file.getSize();

它非常简单,有一些简单的规则:

  • 每当您在then创建承诺时,将其返回- 您不返回的任何承诺都不会在外面等待。
  • 每当您创建多个承诺时, .all它们- 这样它就会等待所有承诺,并且不会消除任何来自其中的错误。
  • 每当您嵌套then s 时,您通常可以在中间返回- then链通常最多 1 级深。
  • 每当您执行 IO 时,它都应该带有承诺- 要么应该在承诺中,要么应该使用承诺来表示其完成。

还有一些提示:

  • 使用.map映射比使用for/push更好- 如果您使用函数映射值, map可以让您简洁地表达一个一个应用操作并聚合结果的概念。
  • 如果它是免费的,并发比顺序执行要好- 最好并发执行事物并等待它们Promise.all比一个接一个地执行事物更好 - 每个都在下一个之前等待。

好的,让我们开始吧:

var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
    return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns

var actions = items.map(fn); // run the function over all items

// we now have a promises array and we want to wait for it

var results = Promise.all(actions); // pass array of promises

results.then(data => // or just .then(console.log)
    console.log(data) // [2, 4, 6, 8, 10]
);

// we can nest this of course, as I said, `then` chains:

var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
    data => Promise.all(data.map(fn))
).then(function(data){
    // the next `then` is executed after the promise has returned from the previous
    // `then` fulfilled, in this case it's an aggregate promise because of 
    // the `.all` 
    return Promise.all(data.map(fn));
}).then(function(data){
    // just for good measure
    return Promise.all(data.map(fn));
});

// now to get the results:

res2.then(function(data){
    console.log(data); // [16, 32, 48, 64, 80]
});

这是一个使用 reduce 的简单示例。 它串行运行,维护插入顺序,并且不需要 Bluebird。

/**
 * 
 * @param items An array of items.
 * @param fn A function that accepts an item from the array and returns a promise.
 * @returns {Promise}
 */
function forEachPromise(items, fn) {
    return items.reduce(function (promise, item) {
        return promise.then(function () {
            return fn(item);
        });
    }, Promise.resolve());
}

并像这样使用它:

var items = ['a', 'b', 'c'];

function logItem(item) {
    return new Promise((resolve, reject) => {
        process.nextTick(() => {
            console.log(item);
            resolve();
        })
    });
}

forEachPromise(items, logItem).then(() => {
    console.log('done');
});

我们发现将可选上下文发送到循环中很有用。 上下文是可选的并且由所有迭代共享。

function forEachPromise(items, fn, context) {
    return items.reduce(function (promise, item) {
        return promise.then(function () {
            return fn(item, context);
        });
    }, Promise.resolve());
}

您的承诺函数如下所示:

function logItem(item, context) {
    return new Promise((resolve, reject) => {
        process.nextTick(() => {
            console.log(item);
            context.itemCount++;
            resolve();
        })
    });
}

我也经历过同样的情况。 我用两个 Promise.All() 解决了。

我认为这是一个非常好的解决方案,所以我在 npm 上发布了它: https ://www.npmjs.com/package/promise-foreach

我认为你的代码会是这样的

var promiseForeach = require('promise-foreach')
var jsonItems = [];
promiseForeach.each(jsonItems,
    [function (jsonItems){
        return new Promise(function(resolve, reject){
            if(jsonItems.type === 'file'){
                jsonItems.getFile().then(function(file){ //or promise.all?
                    resolve(file.getSize())
                })
            }
        })
    }],
    function (result, current) {
        return {
            type: current.type,
            size: jsonItems.result[0]
        }
    },
    function (err, newList) {
        if (err) {
            console.error(err)
            return;
        }
        console.log('new jsonItems : ', newList)
    })

只是为了添加到所提供的解决方案中,在我的情况下,我想从 Firebase 获取多个数据以获取产品列表。 这是我如何做到的:

useEffect(() => {
  const fn = p => firebase.firestore().doc(`products/${p.id}`).get();
  const actions = data.occasion.products.map(fn);
  const results = Promise.all(actions);
  results.then(data => {
    const newProducts = [];
    data.forEach(p => {
      newProducts.push({ id: p.id, ...p.data() });
    });
    setProducts(newProducts);
  });
}, [data]);

暂无
暂无

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

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