链接承诺导致Javascript

时间:2016-10-20 22:53:52

标签: javascript promise

我有两个返回Promise的函数。第一个返回我想要迭代的值列表,并对每个值进行第二次调用,累积到结果以便发回。

function firstCall() {
 return new Promise(returns list of items);
}

function secondCall(someVal) {
  return new Promise(return single value);
}

function doSomething() {
  firstCall().then((response1) => {
    response1.someResult.map((item) => {
      secondCall(item).then((response2) => {
        //how to collect all?
      });
   });
  });
}

关于如何链接这些Promise返回调用并返回最终结果列表的任何建议?

2 个答案:

答案 0 :(得分:2)

我假设您使用的是ES6或某些polyfill(Bluebird等)。如果不是这样,请更新您的问题。如果是这样,您可以将一组Promise发送到Promise.all()并获得一系列答案。



function firstCall() {
  return new Promise((resolve, reject) => {
    resolve([1, 2, 3, 4, 5, 6]);
  })
}

function secondCall(n) {
  return new Promise((resolve, reject) => {
    resolve(n * n);
  })
}

function doSomething() {
  firstCall()
    .then(response1 => {
      console.log(response1);
      let promises = response1.map(r => secondCall(r));

      Promise.all(promises)
        .then(response2 => {
          console.log(response2);
        })
    })
}

doSomething();




答案 1 :(得分:1)

你可以通过传递将取结果的函数来链接promises:

function firstCall() {
  return Promise.resolve([1,2,3,4,5,6]);
};

function secondCall(array) {
  return Promise.all(array.map(square)).then(results => { return results });
}

function square(n){
  return Promise.resolve(n*n);
}

function logger(results){
  console.log(results);
}

function doSomething() {
  return firstCall().then(secondCall).then(logger);
  // you can also chain a .catch() that will bubble up from any chained promise
}

doSomething(); // return value: Promise { <pending> }, logged elements: [ 1, 4, 9, 16, 25, 36 ]