简体   繁体   English

jQuery Deferred诺言

[英]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状态:

  1. Pending (The task isn't processed yet) 待处理 (尚未处理任务)
  2. FullFilled or Resolved (Correctly Processed) 已满已解决 (正确处理)
  3. Rejected (Processed but failed) 已拒绝 (已处理但失败)
  4. Settled (indicates that the task is already processed.) 已解决 (表示任务已被处理。)

 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方法接受两个参数(注意,如果可用,则有第三个参数称为notifyprogress ),如果是完全填充,则第一个被调用,如果被拒绝,则第二个被调用。 。

While the promise is in Pending no callbacks are called! 当Promise在Pending中时,不会调用任何回调!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM