10

例如,我通读了像这样的各种线程。

但它真的让我无法完成以下任务:

我有 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');
}

我试图弄清楚回调但迷路了:(

没有一些简单的方法可以做到这一点吗?就像循环遍历一个数组...

4

5 回答 5

16

这是开始使用jQuery Deferred的好机会。

除了基于回调的解决方案之外,代码可读性强、灵活且可维护性强

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/

于 2012-09-05T03:33:53.953 回答
1

这个想法是你会做类似以下的事情,这样一旦第一个函数完成运行,它就会知道要运行什么,而不是你必须在函数之外自己弄清楚:

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()

于 2012-09-05T03:32:01.897 回答
1

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

    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 个序列,我应该如何跟踪这些东西?不寒而栗...

于 2012-09-05T03:43:17.737 回答
0

已经有一段时间了,我注意到deferredsjquery 文档中的一些内容,特别是when核心 API 函数。

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

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

于 2012-10-18T20:47:06.110 回答
0

我玩过 Promise、Sequence、Exception、Callback 以了解它是如何工作的,最后制作了这段代码。

使用回调调用函数并将结果作为参数依次发送到另一个函数并捕获错误。

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);
}
于 2016-10-03T18:18:22.533 回答