[英]jQuery Deferred promise then
New to the JavaScript Promises and having tough time grasping the concept. JavaScript Promises的新功能,很难掌握这个概念。 It seemed I finally understood, but can't seem to get it working.
看来我终于明白了,但似乎无法使它正常工作。
Here's a simple try: 这是一个简单的尝试:
first = function(){
var deferred = new $.Deferred();
console.log("first running")
return deferred.promise();
}
second = function(){
console.log("second running..sigh..");
}
$(document).ready(function() {
first().then(second);
});
Second is not being called. 第二个没有被调用。
In order for the second function to be called, you need to resolve the deferred returned from the first function: 为了调用第二个函数,您需要解决从第一个函数返回的延迟:
first = function(){
var deferred = new $.Deferred();
console.log("first running");
deferred.resolve(); // <----------resolve the deferred
return deferred.promise();
}
You can also resolve it with arguments so that whatever its resolved with, will be passed as arguments to your second function. 您还可以使用参数来解析它,以便将其解析后的内容作为参数传递给第二个函数。 Here's a fiddle that adds a slight delay to the resolve so it mimics asynchronous behavior and resolves with actual data:
这是一个小提琴,它会稍微延迟解析时间,因此它模仿异步行为并使用实际数据进行解析:
http://jsfiddle.net/1k6tLev8/1/ http://jsfiddle.net/1k6tLev8/1/
You can think a Promise as a task that, in future, will be processed and a result will be returned to all functions that follow the deferred object. 您可以将Promise视为一项任务,将来将对其进行处理并将结果返回给该延迟对象之后的所有函数。
Promises can have 3 + 1 states: 承诺可以具有3 +1状态:
var doSomethingAsync = new Promise(function(resolve, reject) { window.setTimeout(function() { resolve('Hello World'); // OR // reject('You Are Not Welcome') }, 5000); }); doSomethingAsync.then( function(message) { console.log('After few seconds we can finally tell you:', message) }, function(error) { console.log('After few seconds we can finally tell you that: ', error); } );
As you can see in the above snippet the then method of a Promise Object accepts TWO params (note, when available, there is a third parameter called notify or progress ), the first is called in case of fullfilment, the second in case of rejection. 如您在上面的代码段中看到的, Promise对象的then方法接受两个参数(注意,如果可用,则有第三个参数称为notify或progress ),如果是完全填充,则第一个被调用,如果被拒绝,则第二个被调用。 。
While the promise is in Pending no callbacks are called! 当Promise在Pending中时,不会调用任何回调!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.