Javascript 函数排序

Javascript function ordering.

本文关键字:排序 函数 Javascript      更新时间:2023-09-26

我的javascript代码中有3个函数。我想在函数 1 和函数 2 都过度执行后立即调用第三个函数。

func_one();
func_two();
func_three();  // To be called as soon both of the above functions finish executing.

请注意,它们可能需要不同的时间,因为函数 1 和 2 分别用于获取地理位置和一些 ajax 请求。

这个怎么样?

func_one() {
    // Do something
    func_two();
}
func_two() {
    // Do something
    func_three();
}
func_three() {
    // Do something
}

有两种方法可以解决这个问题。第一个是创建回调函数作为现有函数的参数。

function one(param_1 .. param_n, callback) {
    var response = ... // some logic
    if (typeof callback === "function") {
        callback(response);
    }
}

第二种方法是使用承诺,例如:

var p1 = new Promise(
    function(resolve, reject) {
        var response = ... //some logic
        resolve(response);
    }
} 
var p2 = new Promise( ... );
p1.then(function(response1) {
    p2.then(function(response2) {
          //do some logic
    })
})

你可以这样尝试

var oneFinish = false;
var twoFinish = false;
function one(){
    //...
    oneFinish = true; // this value may depends on some logic
}
function two(){
    //...
    twoFinish = true; // this value may depends on some logic
}
function three(){
    setInterval(function(){
        if(oneFinish && twoFinish){
            //...
        }
    }, 3000);
}

由于您的函数func_one并且func_two正在进行服务调用,因此您可以在前一个函数的成功回调时调用这些函数。喜欢

   func_one().success(function(){
       func_two().success(function(){
           func_three();
       });
   });