如何按顺序执行两个异步函数

How to execute two asynchronous function in sequence

本文关键字:两个 异步 函数 何按 顺序 执行      更新时间:2023-09-26

如何使异步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

您想要做的就是所谓的阻塞。在这种情况下,您希望阻止第二个或连续的请求,直到第一个请求完成。

老实说,如果你想屏蔽这个调用,NodeJS不是一个合适的平台。NodeJS将无法像它应该的那样自由地执行。

话虽如此,你可以做一些类似于的事情

var isExecuting = false;
socket_connection.on('request', function (obj) {
    // in other languages you could have done something similar to 
    // while(isExecuting); 
    // but that may not work here.
    var intrvl = setInterval(function(){
        if(!isExecuting){
            clearInterval(intrvl); 
            isExecuting=true; 
            process(obj);  
        }
    },0); // if necessary put some number greater than 0
});
function process(obj){
    readfile(function(content){ //async
        //read content
        //modify content
        writefile(content, function(){ //async
            //write content
          isExecuting = false;
        });
    });
}

拆分您的功能并使用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流控制的顺序调用您的函数。呼叫流程如下所示:

进程()⟶读取文件()⟶readfile完成时调用done⟶然后()⟶writefile()⟶写入文件完成时调用done⟶然后()⟶ ...