【问题标题】:Promise - `then()` not works as expect承诺 - `then()` 不能按预期工作
【发布时间】:2018-04-12 14:23:17
【问题描述】:

我确实有 2 个功能。我正在使用then() 方法链接promise。但我试图在第一个承诺发生后启动second 函数。但现在第二个函数调用为第一个。如何解决这个问题?

或者我的代码有什么问题?

这是我的尝试:

var getData = function(){
    return new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(42); //consoles as second
    }, 5000);
  })
}

var getDataMoreData = function(){
    return new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(43); //consoles as first
    }, 3000);
  })
}



getData().then((data)=> console.log('Data', data)).then(getDataMoreData().then((data)=> console.log('data--', data )));

Live Demo

【问题讨论】:

    标签: javascript asynchronous promise


    【解决方案1】:

    .then 接受 函数 作为参数。当你这样做时

    .then(getDataMoreData()
      .then((data) => console.log('data--', data))
    );
    

    ,它立即调用getDataMoreData()(期望它会返回一个可以放入promise链的函数)。但是getDataMoreData 没有返回一个函数——它返回一个promise。

    then 中立即调用 的任何函数都会立即执行,因为它会尝试构建.then 承诺链。只需在then 中列出函数变量,而不是调用它:

    var getData = function() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(42); 
        }, 500);
      })
    }
    
    var getDataMoreData = function() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(43); 
        }, 300);
      })
    }
    
    
    
    getData()
      .then((data) => console.log('Data', data))
      .then(getDataMoreData)
      .then((data) => console.log('data--', data));

    【讨论】:

    • 这个答案是正确的 - 作为旁注,如果您不需要串行执行,您可以并行运行它们:Promise.all([getData(), getMoreData()].then ((data1, data2) => {})
    猜你喜欢
    • 1970-01-01
    • 2019-02-05
    • 2018-09-19
    • 1970-01-01
    • 2015-11-27
    • 2019-12-03
    • 2019-01-19
    • 1970-01-01
    • 2021-05-01
    相关资源
    最近更新 更多