Koa 2 Promise All (ES7 Async Await)

Promise Async Function
// await 回传必须是一个aysnc function 且返回必须是promise.
async function sleep(key, delay) {
return new Promise(function (resolve, reject) {
try {
setTimeout(function () {
resolve({
key: key,
delay: delay
});
}, delay);
} catch (err) {
reject('error');
}
});
}
非同步併發
// 异步并发
router.get('/demo/2', async (ctx) => {
var demo2 = {};
var startTime = new Date().getTime();
try {
demo2 = await Promise.all([
sleep('a', 50),
sleep('b', 50),
sleep('c', 50),
sleep('d', 50)
]);
} catch (err) {
// 错误处理
console.log(err);
}
const json = {
title: 'demo2 异步并发',
demo2: demo2,
usedTime: `${new Date().getTime() - startTime}/ms`
};
ctx.body = JSON.stringify(json);
});

代碼比Promise 更為簡潔,且更易讀。