如何使异步Javascript函数按顺序执行
socket_connection.on('request', function (obj) {
process(obj);
});
function process(obj){
readfile(function(content){ //async
//read content
//modify content
writefile(content, function(){ //async
//write content
});
});
}
这导致顺序:
read content
read content
modify content
modify content
write content
write content
我如何执行:
read content
modify content
write content
read content
modify content
write content
答案 0 :(得分:0)
您想要做的是被称为阻止。在这种情况下,您希望阻止第二个或连续的请求,直到第一个请求完成。
我的诚实意见 - 如果您想阻止呼叫,NodeJS不是一个合适的平台。 NodeJS将无法像应有的那样自由地运行。
据说你可以做类似的事情 -
maxNumber
答案 1 :(得分:0)
拆分您的功能并使用Promise链接它们
你很幸运。 ECMAScript6 Promise旨在非常巧妙地解决您的问题。从原始代码开始,假设您在process()
函数中按顺序调用这些小函数。
function readfile(callback){
....
callback(content);
}
function writefile(content,callback){
...
callback();
}
您可以宣传他们并按顺序调用它们。
function process(obj){
Promise.resolve(obj){
readfile(done);
})
.then(function(content){
// content read from "readfile" is passed through here as content
return new Promise(function(done,reject){
// Make any modification to "content" as you want here
// ...
writefile(done);
});
})
.then(function(){
// Finish write file! do something
});
}
从上面的代码中,按顺序调用函数,这些函数由Promise流控制。呼叫流程如下所示:
process()⟶readfile()⟶完成在readfile完成时调用 ⟶然后()⟶writefile()⟶完成在writefile完成时调用⟶然后()⟶...