Understanding Promises: Need to combine multiple results

孤者浪人 提交于 2019-12-12 01:23:25

问题


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

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

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?


回答1:


There are multiple ways of handling multiple Promise situation.

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

})();


来源:https://stackoverflow.com/questions/53922275/understanding-promises-need-to-combine-multiple-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!