promise async/await
2019-01-02 18:08 / 已浏览 456 次Promise async/await
强大的回调函数可以构建异步应用
过去为了实现回调:
//可怕的回调地狱 setTimeout(function() { console.log('第一个'); setTimeout(function() { console.log('第二个'); setTimeout(function() { console.log('第三个'); setTimeout(function() { console.log('第四个'); }, 500); }, 1000); }, 500); }, 1000);
使用Promise,解决回调
const resolver = (msg, timeout) => new Promise((resolve) => { console.log(msg); setTimeout(resolve, timeout); }); resolver('第一个', 500) .then(() => resolver('第二个', 500)) .then(() => resolver('第三个', 1000)) .then(() => resolver('第四个', 500));
async、await 已经被标准化。
async、await 都是关键字 , async关键字 是一个函数 返回一个Promise 对象,await 等待的意思,等待什么呢,await等待返回promise对象的一个表达式。
const resolver = (msg, timeout) => new Promise((resolve) => { console.log(msg); setTimeout(resolve, timeout); }); async function run() { await resolver('第一个', 1000); await resolver('第二个', 500); await resolver('第三个', 1000); await resolver('第四个', 500); } run();