【问题标题】:How do you access content from a Promise that is in a then() function, accessing it in the next then() function如何从 then() 函数中的 Promise 访问内容,在下一个 then() 函数中访问它
【发布时间】:2016-07-19 19:03:01
【问题描述】:

你如何从一个 then() 函数中的 Promise 访问内容,在下一个 then() 函数中访问它。

我的问题通过下面的代码大致解释了。

someRandomPromiseFunction().then(function(theArray) {
  var newProm = _.map(theArray, function(arrayItem) {
    return new Promise(function(resolve, reject) {
      resolve(arrayItem);
    });
  }
  Promise.all(newProm).then(function(theArray) {
    return theArray; // How do I access this in the next then() function
  }).catch(function(err) {
    return err;
  });
}).then(function(theArray) {
  console.log(theArray); // I need to access theArray from the Promise.all HERE
});

【问题讨论】:

标签: javascript promise resolve


【解决方案1】:

只要回报承诺

return Promise.all(newProm)...

当您在then() 回调中返回一个promise 时,外部promise 会等到内部promise 解决/拒绝。如果内部承诺解决了,那么该值将传递给外部承诺中的下一个 then() 回调。否则将拒绝值传递给外部 Promise 中的下一个失败回调。

new Promise((resolve,reject)=>{
   resolve("Main promise");
}).then(function(){
   return new Promise((resolve,reject)=>{
       resolve();
   }).then(()=>"Stackoverflow");
}).then(function(data){
  console.log("Outer 'then()' data:",data);
});

【讨论】:

    猜你喜欢
    • 2015-02-20
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多