了解承诺:需要结合多个结果 [英] Understanding Promises: Need to combine multiple results

查看:81
本文介绍了了解承诺:需要结合多个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何处理多个Promise的结果? 在DoNext中说出DoA的结果a和DoB的结果

How do I process the results of more than one Promise? Say the results a of DoA and b of DoB in DoNext

我阅读了 https://developer.mozilla.org/de /docs/Web/JavaScript/Guide/Using_promises 它引入了"then"语法,该语法应取代"doom的回调金字塔",但我不理解以下内容:

I read https://developer.mozilla.org/de/docs/Web/JavaScript/Guide/Using_promises It introduces the "then"-Syntax which is supposed to replace the "callback pyramid of doom" however I don't understand the following:

DoA.then(function(a){
    return DoB(a)
})
.then(function(b){
    DoNext(a,b);
})

在DoNext的调用中,a是未知的.我知道这是因为a仅在第2行的匿名函数中定义.但是,在厄运的回调金字塔"中,我可以访问a,因为在该模式中,DoNext位于匿名函数内,该函数是DoA的成功回调. 我该如何在then-Syntax中处理这个问题?

In the call of DoNext, a is unknown. I understand that this is because a is only defined in the anonymous function in line 2. However in the "callback pyramid of doom" I can access a, because in that pattern DoNext is within the anonymous function that is the success callback of DoA. How do I handle this in then-Syntax?

推荐答案

处理多种Promise情况有多种方法.

There are multiple ways of handling multiple Promise situation.

1-链承诺(虽然很丑)

1- Chain Promise (ugly though)

DoA.then(a => {
    DoB(a).then(.....)

})
.catch(error => console.log(error));

2- Promise.all()

var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]

3- 异步功能(但请阅读详细信息)

3- async function (but read the details)

(async () => {

  const a = await DoA(); // DoA must be a Promise
  const b = await DoB(a); // DoB must be a Promise
  // rest of the code

})();

这篇关于了解承诺:需要结合多个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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