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

时间:2018-01-08 18:34:54

标签: node.js asynchronous

我有一个如下所示的异步功能。请注意,超时功能只是以异步方式运行的其他代码的象征。我希望代码在返回到最终函数之前等待每个系列块完成。

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。

1 个答案:

答案 0 :(得分:1)

您只需移动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'))

相关问题