如何使用 jQuery .When .done

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15594567/
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-08-26 15:23:39  来源:igfitidea点击:

How to use jQuery .When .done

javascriptjquerypromise

提问by Philip Kirkbride

I'm trying to run one function after another function completes.

我试图在另一个函数完成后运行一个函数。

 $.when(saveCanvas(canvas)).done(setWallPaper());

Each function works fine on it's own but when I run the code above it only runs the first function.

每个函数都可以正常工作,但是当我运行上面的代码时,它只运行第一个函数。

What do I need to change?

我需要改变什么?

采纳答案by Philip Kirkbride

Looking back at this now, this seems to be how it works with jQuery:

现在回头看,这似乎是它与 jQuery 的工作方式:

function f1() {
 alert("function one");
}

$.when( f1() ).done(function() {
  alert("function 1 is done running function two");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Note: This is identical to my method I posted in the question so essentially it should have worked. Though jQuery may have changed over the last 3 years. Most likely was a problem with functions being called.

注意:这与我在问题中发布的方法相同,因此基本上它应该有效。尽管 jQuery 在过去 3 年中可能发生了变化。很可能是调用函数的问题。

回答by Luke Shaheen

According to a comment on another SO question, $.whenexpects deferred objects as arguments. If you don't pass anything, the callbacks will be invoked immediately.

根据对另一个 SO 问题的评论,$.when期望延迟对象作为参数。如果你不传递任何东西,回调将被立即调用。

Does setWallPaper()appear to not be working because it is actually being run before saveCancas(canvas)? saveCanvas()is not actually a deferred object, which whenexpects it to be. To make it a deferred object, add dfr = $.Deferred();to the beginning of your saveCanvas()function and return dfr.promise();to the end of it. Check out this SO answerfor more details.

难道setWallPaper()看起来不工作,因为它实际上是被之前运行saveCancas(canvas)saveCanvas()实际上不是延迟对象,它when期望它是。要使其成为延迟对象,请添加dfr = $.Deferred();saveCanvas()函数的开头和return dfr.promise();结尾。查看此 SO 答案以获取更多详细信息。

function saveCanvas(canvas)
{
    dfr = $.Deferred();
    //Your code
    return dfr.promise();
}

Read more: http://api.jquery.com/jQuery.when/

阅读更多:http: //api.jquery.com/jQuery.when/

回答by Crash Override

another wild guess:

另一个疯狂的猜测:

$.when(saveCanvas(canvas)).done(function(){
    setWallPaper()
});