Promise 函数
上述的 "计时器" 程序看上去比函数瀑布还要长,所以我们可以将它的核心部分写成一个 Promise 函数:
实例
functionprint(delay, message){ returnnewPromise(function(resolve, reject){ setTimeout(function(){ console.log(message); resolve(); }, delay); });}
然后我们就可以放心大胆的实现程序功能了:
实例
print(1000, "First").then(function(){ returnprint(4000, "Second");}).then(function(){ print(3000, "Third");});
这种返回值为一个 Promise 对象的函数称作 Promise 函数,它常常用于开发基于异步操作的库。