基本承诺创造

这是一个非常简单的函数示例,“ 承诺在给定时间过去后继续”。它通过创建一个新的 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");
});