Nodejs按顺序运行任务

Par*_*wan 4 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()]);
Run Code Online (Sandbox Code Playgroud)

输出总是世界问候.

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

Div*_*ani 6

Async要求你使用callback.请点击链接查看一些示例.以下代码应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);
    }
});
Run Code Online (Sandbox Code Playgroud)

注意,callback()setTimeout()函数内部调用它以便等待console.log('hello').