Nodejs 运行 任务顺序

Nodejs run task in sequence

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

例如,

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

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

并且输出始终是 world hello。

我使用的库对吗?我不认为这个问题看起来微不足道,但我真的不知道如何在一个长任务

之后将一个短任务强制到 运行

你可以使用回调,它是 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
})

Async 要求您使用 callback。按照 this link 查看一些示例。以下代码应正确输出 hello world

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

function world(callback) {
    console.log("world");
    callback();
}

async.series([hello, world], function (err, results) {
    // results is an array of the value returned from each function
    // Handling errors here
    if (err)    {
        console.log(err);
    }
});

请注意,callback() 是在 setTimeout() 函数内部调用的,因此它会等待 console.log('hello')

您可以使用承诺而不是回调。所以您的代码将如下所示:

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

   function world(){
    console.log("world");
      }
    return Q.fcall(function() {
       hello();
    })
   .then(function(resultOfHelloFunction){
      world();
 });

World() 函数只会在 hello() 函数执行完成时执行。

P.S :我正在使用 Q 库来实现 promisify 函数。使用其他库(例如bluebird)来实现同样的事情是完全可以的。

使用承诺

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);
  });