我希望能够使用Promise.all或Promise.map(Bluebird)开始执行Promises数组,而该数组仍在填充,然后在填充数组时等待结果。这在处理需要很长时间加载或可能导致内存限制的大型数据集时非常有用。
今天如何工作的示例,使用mongodb游标加载数据(使用bluebird的Promise.map):
// This is a time-intensive operation
// and requires loading all values into
// memory before proceeding
const dataArray = await cursor.toArray();
// Start doing work after all objects are in memory
await Promise.map(dataArray, doSomeWork);
// done
我希望它如何工作的示例:
const dataArray = [];
const minItems = N;
let promiseMap = null;
// Populate the data array one item at a time
while (await cursor.hasNext()) {
dataArray.push(await cursor.next());
if (!promiseMap && dataArray.length > minItems) {
// Start doing work once there is some data to
// work with and keep filling the array
promiseMap = Promise.map(dataArray, doSomeWork);
}
}
// Once done filling the array, wait for all promises to resolve
await promiseMap;
// done
这是可能的,还是在继续执行之前有一个静态的promises数组是一个很难的要求?
答案 0 :(得分:1)
从the docs看起来eachAsynch
可以处理doSomeWork
函数返回的承诺,等待它继续完成...
var cursor = someQuery.cursor();
cursor.eachAsync(doc => doSomeWork(doc)).then(result =>
/* after all docs processed */);