Promise.all()。然后()解决? [英] Promise.all().then() resolve?

查看:92
本文介绍了Promise.all()。然后()解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Node 4.x.当你有一个 Promise.all(promises).then()解决数据并将其传递给下一个的正确方法是什么。 ()

Using Node 4.x. When you have a Promise.all(promises).then() what is the proper way to resolve the data and pass it to the next .then()?

我想做这样的事情:

Promise.all(promises).then(function(data){
  // Do something with the data here
}).then(function(data){
  // Do more stuff here
});

但是我不知道如何将数据送到第二个。然后()。我不能在第一个 .then()中使用 resolve(...)。我想我可以这样做:

But I'm not sure how to get the data to the 2nd .then(). I can't use resolve(...) in the first .then(). I figured out I can do this:

return Promise.all(promises).then(function(data){
  // Do something with the data here
  return data;
}).then(function(data){
  // Do more stuff here
});

但这似乎不是正确的方法......什么是正确的方法对此?

But that doesn't seem like the proper way to do it... What is the right approach to this?

推荐答案


但这似乎不是正确的方法。

But that doesn't seem like the proper way to do it..

这确实是做到这一点的正确方法(或者至少是 正确的方法) 。这是promises的一个关键方面,它们是一个管道,数据可以由管道中的各种处理程序进行按摩。

That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.

示例:

const promises = [
  new Promise(resolve => setTimeout(resolve, 0, 1)),
  new Promise(resolve => setTimeout(resolve, 0, 2))
];
Promise.all(promises)
  .then(data => {
    console.log("First handler", data);
    return data.map(entry => entry * 10);
  })
  .then(data => {
    console.log("Second handler", data);
  });

catch 为简洁省略了处理程序。在生产代码中,总是传播承诺,或处理拒绝。)

(catch handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)

我们从中看到的输出是:

The output we see from that is:


First handler [1,2]
Second handler [10,20]

...因为第一个处理程序获得了两个承诺的分辨率( 1 2 )作为一个数组,然后创建一个新数组,每个数组乘以10并返回它。第二个处理程序获取第一个处理程序返回的内容。

...because the first handler gets the resolution of the two promises (1 and 2) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.

如果您正在执行的其他工作是同步的,您也可以将放在中第一个处理程序:

If the additional work you're doing is synchronous, you can also put it in the first handler:

示例:

const promises = [
  new Promise(resolve => setTimeout(resolve, 0, 1)),
  new Promise(resolve => setTimeout(resolve, 0, 2))
];
Promise.all(promises)
  .then(data => {
    console.log("Initial data", data);
    data = data.map(entry => entry * 10);
    console.log("Updated data", data);
    return data;
  });

...但如果它是异步的你就赢了我想这样做,因为它最终得到嵌套,嵌套很快就会失控。

...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.

这篇关于Promise.all()。然后()解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆