使异步代码在执行之前等待结束



我有一个异步函数,如下所示。请注意,超时函数只是以异步方式运行的其他代码的符号。我希望代码等到每个系列块完成,然后再返回到最后一个函数。

var async = require('async')
var param1 = 'foobar'
function withParams(param1, callback) {
    console.log('withParams function called')
    console.log(param1)
    callback()
}
function withoutParams(callback) {
    if(true){
        console.log("withoutParams function called")
        setTimeout(function () {
            console.log("test")        }, 10000);
        callback()
    }
    else{
        console.log('This part will never run')
        callback()
    }
}
async.series([
    function(callback) {
        withParams(param1, callback)
    },
    withoutParams
], function(err) {
    console.log('all functions complete')
})

输出为

withParams function called
foobar
withoutParams function called
all functions complete
test

我希望输出是

withParams function called
foobar
withoutParams function called
test
all functions complete

有没有其他异步版本在调用结束部分之前等待最后一个块完成function(err){...? 我正在学习nodejs。

你只需要移动你的callback

function withoutParams(callback) {
    if(true){
        console.log("withoutParams function called")
        setTimeout(function () {
            console.log("test")
            callback() //  <-- HERE
        }, 1000);
    }
    else{
        console.log('This part will never run')
        callback()
    }
}

当然,您只需使用 promises 即可在没有 async 库的情况下获得相同的结果:

var param1 = 'foobar'
function withParams(param1) {
  console.log('withParams function called')
  console.log(param1)
}
function withoutParams() {
  return new Promise((resolve, reject) => {
    if (true) {
      console.log("withoutParams function called")
      setTimeout(function() {
        console.log("test")
        resolve()
      }, 1000);
    } else {
      console.log('This part will never run')
      reject()
    }
  })
}
withParams(param1)
withoutParams()
  .then(() => console.log('all functions complete'))

最新更新