我是 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。
我使用的库对吗?我不是这个问题看起来微不足道,但我真的不知道如何在一个长的任务之后强制执行一个短的任务
最佳答案
异步
要求您使用回调
。关注this链接以查看一些示例。以下代码应正确输出 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')
.
关于node.js - Nodejs按顺序运行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40966694/