用两个参数异步JavaScript函数 [英] Two Async Javascript Functions with Parameters
问题描述
我的问题完全取决于previous <一个href=\"http://stackoverflow.com/questions/6392055/javascript-testing-two-asynch-calls-before-going-to-third-function\">question:
My question totally depends on a previous question:
关于方法3号(下称柜台一节):如果 handleCompletion
从需要的值 startOtherAsync
,以完成其工作。我们怎样才能实现呢?
Regarding approach number 3 (the "counter" one): If handleCompletion
needs a value from startOtherAsync
in order to do its job. How can we implement that?
请注意,该值从 startOtherAsync
(可能是一个参数)未来将 startAsync
伤心,无法调用 handleCompletion
了。
Note that that value coming from startOtherAsync
(probably a parameter) will make startAsync
sad and unable to call handleCompletion
anymore.
推荐答案
这实际上是用承诺一个完美的地方。所有jQuery的Ajax调用默认情况下,这意味着回报的承诺,你可以简单地把它们连在一起:
This is actually a perfect place to use promises. All the jQuery Ajax calls return promises by default which means you can simply chain them together:
$.ajax({/*snip*/}).then(
function(result){
doSomethingWithResult(result);
return $.ajax({/*snip*/});
}).then(function(result){
doSomeFinalProcessing(result);
});
当然,一个的jsfiddle证明这一点发生。
下面是一个更新的提琴,说明如何多个同时承诺结合起来,并结合他们的结果。
Here is an updated fiddle that shows how to combine multiple simultaneous promises and combine their results.
http://jsfiddle.net/jwcarroll/U3N9u/
而code:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function doStuffLater(msg){
var def = $.Deferred();
setTimeout(function(){
def.resolve(msg);
}, getRandomInt(300, 1000));
return def.promise();
}
function needsBothReturns(one, two){
console.log({one:one, two:two});
}
var first = doStuffLater("Sent First");
var second = doStuffLater("Sent Second");
$.when(first, second).done(function(result1, result2){
needsBothReturns(result1, result2);
});
这篇关于用两个参数异步JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!