If you use Node7, you can use async/await to write. I just posted the blog From Hell to Heaven, and I also wrote about understanding async/await before.
If Node7 is not used, Async library's waterfall() should be able to handle your problem. For details, please refer to the first blog above. waterfall() 应该可以处理你的问题,具体参考上述第一篇博客。
async function doIt() {
for (var i = 0; i < 10; i++) {
const body = await new Promise((resolve, reject) => {
request(`${queryStringSql}&page=${i}`, function(error, response, body) {
if (error || response.statusCode != 200) {
reject(error);
} else {
resolve(body);
}
});
});
console.log(body);
}
}
doIt();
其它
Async、Q、Bluebird、co 这些库都有办法实现,但应该都不是用 for
You can also encapsulate Promise yourself and then handle it through then - you can’t use for anyway...🎜
Parallel processing and reordering results
🎜I looked at it and I think you can fetch 10 pages of data asynchronously at the same time. After fetching, sort it according to a certain identifier (page number), and then process it in order🎜
rrreee
async/await
rrreee
Others
🎜Libraries such as Async, Q, Bluebird, and co all have ways to implement it, but they should not use for loops. 🎜
If you use Node7, you can use async/await to write. I just posted the blog From Hell to Heaven, and I also wrote about understanding async/await before.
If Node7 is not used, Async library's
waterfall()
should be able to handle your problem. For details, please refer to the first blog above.waterfall()
应该可以处理你的问题,具体参考上述第一篇博客。也可以自己封装 Promise,然后通过 then 来处理——反正也是不能用 for 的……
并行处理再排序结果
我看了下,我觉得你这个需要可以同时异步去取 10 页的数据,取完之后按一定的标识(页码)进行排序,再按顺序来加工
async/await
其它
Async、Q、Bluebird、co 这些库都有办法实现,但应该都不是用
You can also encapsulate Promise yourself and then handle it through then - you can’t use for anyway...🎜for
Parallel processing and reordering results
🎜I looked at it and I think you can fetch 10 pages of data asynchronously at the same time. After fetching, sort it according to a certain identifier (page number), and then process it in order🎜 rrreeeasync/await
rrreeeOthers
🎜Libraries such as Async, Q, Bluebird, and co all have ways to implement it, but they should not usefor
loops. 🎜There are many solutions, you can adopt them here
q
This will serially request the addresses in the urls array.
For details, you can read this article I wrote about nodejs q module
Or you can use the generator and co modules in ES6 to achieve it
Promise recursive call
reduce is enough. Think specifically
Just use Bluebird’s Promise.mapSeries method.