示例
首先查看一些示例 - 滚动下方查看说明。
回调:
异步和采用 Node 样式回调的函数的示例:
async.parallel([
(cb) => {
setTimeout(() => {
cb(null, 'one');
}, 200);
},
(cb) => {
setTimeout(() => {
cb(null, 'two');
}, 100);
},
],
(err, results) => {
if (err) {
// there was an error:
console.log('Error:', err);
return;
}
// we have ['one', 'two'] in results:
console.log('Results:', JSON.stringify(results));
});
承诺:
使用返回承诺的函数的示例 - 使用 Bluebird 的 delay() 函数:
const { delay } = require('bluebird');
Promise.all([
delay(200, 'one'),
delay(100, 'two'),
]).then((results) => {
// we have ['one', 'two'] in results:
console.log('Results:', JSON.stringify(results));
}).catch((err) => {
// there was an error:
console.log('Error:', err);
});
ES2017async/await:
使用异步/等待:
const { delay } = require('bluebird');
try {
const results = await Promise.all([
delay(200, 'one'),
delay(100, 'two'),
]);
// we have ['one', 'two'] in results:
console.log('Results:', JSON.stringify(results));
} catch (err) {
// there was an error:
console.log('Error:', err);
}
我使用JSON.stringify() 明确说明results 中的数据格式是什么。
请注意,即使第一个值排在最后,仍会保留原始顺序。
最后一个示例必须在使用 async 关键字声明的函数内运行,或者像这样包装在 (async () => { ... })() 中:
(async () => {
try {
const results = await Promise.all([
delay(200, 'one'),
delay(100, 'two'),
]);
// we have ['one', 'two'] in results:
console.log('Results:', JSON.stringify(results));
} catch (err) {
// there was an error:
console.log('Error:', err);
}
})();
生成器和协程:
在不支持 async/await 的情况下,您可以使用一些基于生成器的协程,例如来自 Bluebird 的协程:
const { delay, coroutine } = require('bluebird');
coroutine(function* () {
try {
const results = yield Promise.all([
delay(200, 'one'),
delay(100, 'two'),
]);
// we have ['one', 'two'] in results:
console.log('Results:', JSON.stringify(results));
} catch (err) {
// there was an error:
console.log('Error:', err);
}
})();
说明
有很多方法可以做到这一点,这完全取决于您要运行的函数类型。
如果您想运行传统的 Node 风格函数,将错误优先回调作为最后一个参数,那么并行或串行运行这些函数的最流行方法是 npm 上的 async 模块:
在 ES6 中没有对类似的东西的内置支持,因为那些错误优先回调实际上是 Node 的东西,在 Node 之外的 JavaScript 中不是很流行。
ES6/ES7/ES8 朝着返回 Promise 的函数(而不是接受回调的函数)的方向发展,并且有一个新的 async/await 语法使它们看起来有点像同步,使用 try/catch 进行错误处理。
因此,Node 中最流行的组合接受回调的函数的方式是异步模块:
使用 Promise 的一个流行模块是 Bluebird:
对于更高级的任务,有 Task.js:
查看这些答案了解更多信息: