-->

排序函数调用javascript中 - 是回调的唯一途径?(sequencing function

2019-07-31 09:11发布

我通过各种线程像阅读这样一个的例子。

但它确实脱离了我如何做到以下几点:

我有4种功能,并希望他们陆续发生的顺序。 请注意,他们是不正确的顺序,使对方了解我的观点。 我想要的结果将输出“1,2,3,4'

function firstFunction(){
  // some very time consuming asynchronous code...
  console.log('1');
}
function thirdFunction(){
  // definitely dont wanna do this until secondFunction is finished
  console.log('3');
}
function secondFunction(){
  // waits for firstFunction to be completed
  console.log('2');
}
function fourthFunction(){
  // last function, not executed until the other 3 are done.
  console.log('4');
}

我试图找出回调,但我迷路:(

是不是有一些简单的方法来做到这一点? 想通过数组循环...

Answer 1:

这是一个很好的机会,开始使用jQuery的递延 。

除了基于回调的解决方案的代码是可读的,灵活和高度可维护

http://jsfiddle.net/zerkms/zJhph/

function firstFunction(){
  var d = $.Deferred();
  // some very time consuming asynchronous code...
  setTimeout(function() {
    console.log('1');
    d.resolve();
  }, 1000);
  return d.promise();
}
function thirdFunction(){
  var d = $.Deferred();
  // definitely dont wanna do this until secondFunction is finished
  setTimeout(function() {
    console.log('3');
    d.resolve();
  }, 1000);
  return d.promise();
}
function secondFunction(){
  var d = $.Deferred();
  setTimeout(function() {
    console.log('2');
    d.resolve();
  }, 1000);
  return d.promise();
}
function fourthFunction(){
  var d = $.Deferred();
  // last function, not executed until the other 3 are done.
  setTimeout(function() {
    console.log('4');
    d.resolve();
  }, 1000);
  return d.promise();
}

firstFunction().pipe(secondFunction).pipe(thirdFunction).pipe(fourthFunction);​

PS:作为异步代码的示例我使用setTimeout 。 最主要的是,在异步部分结束时,您需要调用d.resolve()继续链的方法。

延伸阅读: http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/



Answer 2:

我们的想法是,你会做类似下面这样一旦第一个功能是进行运行,它会知道什么,而不是奔向你必须搞清楚你自己之外的功能:

function firstFunction(callback){
  // some very time consuming asynchronous code...
  console.log('1');

  return callback(function(){
    alert("Second function finished.");
    return true;
  });
}
function secondFunction(callback){
  // waits for firstFunction to be completed
  console.log('2');

  return callback();
}

firstFunction(secondFunction);

此外查找.apply().call()



Answer 3:

如果我使用的回调,我的工作解决方案现在看起来是这样的:

    one(two);
    function one(callb){
        console.log('1');
        callb(three);
    }
    function four(){
        console.log('4');
    }
    function two(callb){
        console.log('2');
        callb(four);
    }
    function three(callb){
        console.log('3');
        callb();
    }

我觉得可怕。 我怎么让这些东西的轨道,如果有超过2-3序列? 不寒而栗...



Answer 4:

它已经有一段时间,我发现了一些关于deferreds jQuery的文档中,特别是when核心API函数。

$.when( $.ajax("test.aspx") ).then(function(ajaxArgs){ 
     alert(ajaxArgs[1]); /* ajaxArgs is [ "success", statusText, jqXHR ] */
});

取自代码示例http://jqapi.com/#p=jQuery.when



Answer 5:

我已经打了诺言,序列,异常回调了解它是如何工作的,并最终做出这个代码。

调用函数与回调的顺序发送结果作为参数传递给另一个函数,有一个捕获错误。

function firstFunction(par) {
    return new Promise(function (resolve, reject) {
        console.log("start " + par);
        setTimeout(function (par) {
            console.log(par);
            resolve(par + 1);
        }, 1000, par);
    });
}
function secondFunction(par) {
    return new Promise(function (resolve, reject) {
        console.log("start " + par);
        setTimeout(function (par) {
            console.log(par);
            try{
                throw "Let's make an error...";
            }
            catch(err)
            {
                reject(err);
            }
            resolve(par + 1);
        }, 1000, par);
    })
}
function thirdFunction(par) {
    return new Promise(function (resolve, reject) {
        console.log("start " + par);
        setTimeout(function (par) {
            console.log(par);
            resolve(par + 1);
        }, 1000, par);
    });
}

function CatchError(error) {
    console.log("Exception: " + error);
}

//Break all chain in second function
function ChainBrake() {
    firstFunction(1)
    .then(secondFunction)
    .then(thirdFunction)
    .catch(CatchError);    
}

//Log error and continue executing chain
function ChainContinue() {
    firstFunction(1)
    .catch(CatchError)
    .then(secondFunction)
    .catch(CatchError)
    .then(thirdFunction)
    .catch(CatchError);
}


文章来源: sequencing function calls in javascript - are callbacks the only way?