基本承諾創造
這是一個非常簡單的函式示例,“ 承諾在給定時間過去後繼續”。它通過建立一個新的 Deferred
物件來實現,該物件稍後解決並返回 Deferred 的承諾:
function waitPromise(milliseconds){
// Create a new Deferred object using the jQuery static method
var def = $.Deferred();
// Do some asynchronous work - in this case a simple timer
setTimeout(function(){
// Work completed... resolve the deferred, so it's promise will proceed
def.resolve();
}, milliseconds);
// Immediately return a "promise to proceed when the wait time ends"
return def.promise();
}
並使用這樣的:
waitPromise(2000).then(function(){
console.log("I have waited long enough");
});