[英]jQuery Deferred promise then
JavaScript Promises的新功能,很難掌握這個概念。 看來我終於明白了,但似乎無法使它正常工作。
這是一個簡單的嘗試:
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);
});
第二個沒有被調用。
為了調用第二個函數,您需要解決從第一個函數返回的延遲:
first = function(){
var deferred = new $.Deferred();
console.log("first running");
deferred.resolve(); // <----------resolve the deferred
return deferred.promise();
}
您還可以使用參數來解析它,以便將其解析后的內容作為參數傳遞給第二個函數。 這是一個小提琴,它會稍微延遲解析時間,因此它模仿異步行為並使用實際數據進行解析:
您可以將Promise視為一項任務,將來將對其進行處理並將結果返回給該延遲對象之后的所有函數。
承諾可以具有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); } );
如您在上面的代碼段中看到的, Promise對象的then方法接受兩個參數(注意,如果可用,則有第三個參數稱為notify或progress ),如果是完全填充,則第一個被調用,如果被拒絕,則第二個被調用。 。
當Promise在Pending中時,不會調用任何回調!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.