当其他第一个函数完成时调用函数(回调)

Call function when other first function finished (callback)

本文关键字:函数 回调 调用 完成时 其他 第一个      更新时间:2023-09-26

我使用jquery 1.8.2
我有这些函数(下面),但我想调用bar()函数时,foo()已经完成,这不会发生。我该怎么做呢?

function foo() {
  //something time consuming
  console.log("foo")
}
function bar() {
  console.log("bar");
}
function helloWorld() {
  foo();
  bar();
}

您有几种方法可以做到这一点。现在,我能想到两个我经常使用的。第一种方法(也是最容易理解的)是使用回调。只需将想要调用的第二个函数作为参数传递给第一个函数。

function foo(callback) {
    setTimeout(function(){
        console.log("foo");
        callback();
    }, 500);
}
function bar() {
    console.log("bar");
}
function helloWorld() {
    foo(bar)
}
helloWorld();

(JSFiddle)

这并不需要任何额外的库,但是当你有很多异步的东西时,代码很快就会变得一团糟。

另一个解决方案,有点难以理解,但更强大,是使用承诺。

通过提供适当的方法来处理异步代码,

promise是处理异步代码的好方法。唯一的缺点是您需要学习它们,并使用外部库。

EDIT:正如所指出的,我没有使用JQuery API。下面是使用它的样子:

function foo() {
    var deferred = jQuery.Deferred();
    setTimeout(function(){
        console.log("foo");
        deferred.resolve();
    }, 500);
    return deferred.promise();
}
function bar() {
    console.log("bar");
}
function helloWorld() {
  foo().then(bar);
}
helloWorld();

(JSFiddle)

下面的例子是基于Q.

function foo() {
    var deferred = Q.defer();
    setTimeout(function(){
        console.log("foo");
        deferred.resolve();
    }, 500);
    return deferred.promise;
}
function bar() {
    console.log("bar");
}
function helloWorld() {
    foo().then(bar);
}
helloWorld();
(JSFiddle)

function method1(){//一些代码

}

function method2(){
   // some code
}
$.ajax({
   url:method1(),
   success:function(){
   method2();
}
})

如下:

function foo() {
  var deferred=$.Deferred(); //create a deferred object
  console.log("foo");
  return deferred.resolve() //once logging done resolve it and send back
}
function bar() {
  console.log("bar");
}
function helloWorld() {
  $.when(foo()).done(bar()); //you can use $.when and done
}
$(document).ready(function(){
  helloWorld();  
})