在另一个函数完成后再调用一个函数

call a function after another function is completed

本文关键字:函数 一个 调用 另一个      更新时间:2023-09-26

我正在尝试调用加载()完成后的另一个函数。我首先尝试使用alert()进行检查,但是,我在load()完成之前看到了警报。我能够在load()函数中成功加载内容。但是,alert()为空。

$(document).ready(function(){   
    load();
    $.when(load()).done(function(){
        alert((document.getElementById('item').innerHTML));
    });        
    function load()
    { 
        $("#item").load("/somepage.aspx", function (response, status, xhr){
              if ( status == "error" ) {
                var msg = "error: ";
                $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
              }
        });                         
    };
});

你需要load()返回一个承诺,然后你把这个承诺传递给$.when

.load()不返回一个承诺,它返回它被调用的jQuery集合(为了链接的目的)。你可以重写load()使用$.get()代替,它返回一个jQXHR,实现Deferred(这是jQuery的承诺类)。

var p = load();
$.when(p).done(function() {
    alert($("#item").html());
});
function load() {
    return $.get("/somepage.aspx", function (response, status, xhr){
        $("#item").html(response);
        if ( status == "error" ) {
            var msg = "error: ";
            $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
        }
    });
}

你实际上不需要使用$.when,你可以直接写:

p.done(function() { ... });

您可以使用回调函数并将代码更新为

$(document).ready(function(){   
    load(function(){
        alert((document.getElementById('item').innerHTML));
    });
    function load(callback)
    { 
        $("#item").load("/somepage.aspx", function (response, status, xhr){
              if ( status == "error" ) {
                var msg = "error: ";
                $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
              }
              if(callback) {
                   callback();
              }
        });                         
    };
});

你可以使用在大多数主流浏览器中已经实现的新的Promises API。

var jsonPromise = new Promise(function(resolve, reject) {
    // do a thing, possibly async, then…
    if ( /* everything turned out fine */ ) {
        resolve("Stuff worked!");
    } 
    else {
        reject(Error("It broke"));
   }
});
jsonPromise.then(function(data) {
    console.log(result); // "Stuff worked!"
}, function(err) {
    console.log(err); // Error: "It broke"
});