【发布时间】:2018-01-06 00:43:28
【问题描述】:
我在 Express/Sequelize 应用中做了很多基于 Promise 的操作。为了控制数据流,我想尽可能地遵循promise模型。
这是我目前正在做的事情:
AreaList.forEach( area => {
distances.push({
target: tgt,
source: area,
distance: areaController.calcDist(tgt, area),
country: areaController.determineCountry(area)
}).then(() => { //this is where I would like to have the .then() function, but get the error.
distances.sort((a1, a2) =>{
return a1.distance - a2.distance;
}).filter(area => area.country === country)
.forEach(area => {
Insider.findAll({
where: {
areaCode: area.source,
country: area.country,
language: language,
gender: gender
}
}).then( insider => {
returnUsers.push(insiders);
}).then(_ => {
returnUsers = returnUsers.splice(0,10);
res.status(200).send(returnUsers);
});
});
});
});
如何为数组提供.then(),或模拟.then()?
【问题讨论】:
-
数组的
push函数返回数组中新的元素个数,没有then函数用于数字。由于push函数不能异步工作,所以这里不需要使用promise,只需将push新项添加到数组中,然后继续sort。 -
你不需要
then函数,只需结束命令,写一个温柔的;并返回下一行:推送函数是同步的。 -
我假设
AreaList是一个项目数组。您想处理一个接一个的项目(串行),同时处理(并行)还是并行,但每个周期的最大 x 数量(例如每秒最多 5 个)或最大 x 活动量(例如不超过 5 个活动连接) ?您的代码中有哪些异步函数?areacontroller函数是同步的还是异步的?我假设Insider.findAll是异步的,那是唯一的异步函数吗? -
忘记了。如果一个失败了,你想要那些成功的还是失败的?
-
AreaList应该串行处理。areaController是这段代码的来源模块,是的,findAll()函数是异步的,这就是为什么我对这种异步和同步代码的混合感到困惑。
标签: javascript arrays promise