Nodejs按顺序运行任务

时间:2016-12-05 03:32:53

标签: node.js async.js

我是node.js的新手,我不知道如何在另一个函数之前执行settimeout函数,

例如,

var async = require('async');
function hello(){
    setTimeout(function(){
        console.log('hello');
    },2000);}

function world(){
    console.log("world");
}
async.series([hello,world()]);

并且输出总是世界问候。

我正在使用图书馆吗?我不是这个问题似乎微不足道但我真的不知道如何强迫一个短期任务在长期之后运行

2 个答案:

答案 0 :(得分:2)

使用承诺

function hello(){
    return new Promise(function(resolve, reject) {
        console.log('hello');
        resolve();
    });
}

function world(){
   return new Promise(function(resolve, reject) {
      console.log("world");
      resolve();
    });
}


  hello()
  .then(function(){
     return world()
  })
  .then(function(){
    console.log('both done');
  })
  .catch(function(err){
     console.log(err);
  });

答案 1 :(得分:-1)

您可以使用作为nodejs核心的回调。

var fun1 = function(cb){
 // long task
 // on done 
 return cb(null, result);
}

var fun2 = function(cb){
 return cb(null, data);
}

fun1(function(err, result){
 if(!err){
   fun2(function(er, data){
    // do here last task

   })
 }
}

// to avoid pyramid of doom use native promises

func1 (){
 return new Promise((resolve, reject) => {
   // do stuff here
   resolve(data)
 })

}
func2(){
  return new Promise((resolve, reject) => {
    resolve(data);
  })
}

然后使用:

打电话给他们
func1.then((data) => {
 return func2();
})
.then((resule) => {
 //do here stuff when both promises are resolved
})