你可以抛弃async
完全并且去async/await
很容易。
承诺您的请求和使用async/await
只要转动request
into a Promise
所以你可以await
on it.
更好的是只需使用请求-承诺-本机 https://github.com/request/request-promise-native已经使用原生 Promises 包装了请求。
串行示例
从那时起,它就是一个灌篮async/await
:
const rp = require('request-promise-native')
const users = [1, 2, 3, 4]
const results = []
for (const idUser of users) {
const result = await rp('http://foo.com/users/' + idUser)
results.push(result)
}
并行示例
现在,上述解决方案的问题是它很慢 - 请求串行运行。大多数时候这并不理想。
如果下一个请求不需要上一个请求的结果,只需继续执行Promise.all
开火parallel要求。
const users = [1, 2, 3, 4]
const pendingPromises = []
for (const idUser of users) {
// Here we won't `await` on *each and every* request.
// We'll just prepare it and push it into an Array
pendingPromises.push(rp('http://foo.com/users/' + idUser))
}
// Then we `await` on a a `Promise.all` of those requests
// which will fire all the prepared promises *simultaneously*,
// and resolve when all have been completed
const results = await Promise.all(pendingPromises)
错误处理
错误处理在async/await
由 plain-old 提供try..catch
块,为了简洁起见我省略了它们。