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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31438428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:47:13  来源:igfitidea点击:

call a function after another function is completed

javascriptjqueryajax

提问by smtp

I am trying to call another function after load() is completed. I first tried to check with alert(), however, I see the alert before load() is done. I am able to successfully load content in load() function. However, alert() is empty.

我试图在 load() 完成后调用另一个函数。我首先尝试使用 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 );
              }
        });                         
    };
});

采纳答案by Barmar

You need load()to return a promise, and then you pass this promise to $.when.

您需要load()返回一个承诺,然后将此承诺传递给$.when

.load()doesn't return a promise, it returns the jQuery collection that it was called on (for chaining purposes). You can rewrite load()using $.get()instead, which returns a jQXHR, which implements Deferred(that's jQuery's promise class).

.load()不返回承诺,它返回调用它的 jQuery 集合(用于链接目的)。你可以改写load()using $.get(),它返回一个jQXHR,它实现了Deferred(这是jQuery的promise类)。

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 );
        }
    });
}

You don't actually need to use $.when, you can just write:

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

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

回答by Nikhil Aggarwal

You can use callback functions and update your code to following

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

$(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();
              }
        });                         
    };
});

回答by Sagi

You can use the new PromisesAPI which is already implemented in most major browsers.

您可以使用已在大多数主要浏览器中实现的新PromisesAPI。

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"
});