javascript - 按顺序执行promises map
问题描述
我编写了一个在循环(映射)中调用的函数,并且该函数正在使用 Promise。现在,我希望该函数在调用下一个实例之前同步运行并退出。
function t1(){
let arr1 = [1,2,3,4,5];
return Promise.map(arr1, (val) =>{
const params = {
"param1" : val1
};
return t2(params);
});
}
function t2(event){
return Promise.resolve()
.then({
//do something
//code doesn't reach here in sync manner. all five instance are invoked and then code reaches here for first instance and so on
})
.then({
//promise chaining. do something more
})
}
t2 被调用五次,但我希望每个实例仅在实例返回值之前被调用。目前它的行为不是那样,而是并行调用该函数五次。
由于项目限制,我无法使用 async/await。
解决方案
您当前代码的问题在于Promise.prototype.map
,像 一样forEach
,不会等待在其中调用的异步函数完成。await
(除非您使用or明确地告诉解释器这样做,否则不会等待任何异步调用.then
)
等待t1
每次调用t2
:
async function t1(){
let arr1 = [1,2,3,4,5];
const results = [];
for (const val of arr1) {
results.push(await t2(val));
}
return results;
}
或者,如果您想使用reduce
而不是async
/ await
:
const delay = () => new Promise(res => setTimeout(res, 500));
function t1(){
let arr1 = [1,2,3,4,5];
return arr1.reduce((lastProm, val) => lastProm.then(
(resultArrSoFar) => t2(val)
.then(result => [...resultArrSoFar, result])
), Promise.resolve([]));
}
function t2(event){
return delay().then(() => {
console.log('iter');
return event;
});
}
t1()
.then(results => console.log('end t1', results));
或者,如果您需要将顺序功能封装在 t2 中,则让 t2 具有它生成的前一个 Promise 的半持久变量:
const delay = () => new Promise(res => setTimeout(res, 500));
const t1 = () => {
return Promise.all([1, 2, 3, 4].map(t2));
};
const t2 = (() => {
let lastProm = Promise.resolve();
return (event) => {
const nextProm = lastProm
.catch(() => null) // you may or may not want to catch here
.then(() => {
// do something with event
console.log('processing event');
return delay().then(() => event);
});
lastProm = nextProm;
return nextProm;
};
})();
t1().then(results => console.log('t1 done', results));
推荐阅读
- apache-spark - 如何在 UDF 中创建数据框
- h2o - H2o Driverless ai最新稳定1.8版本支持图像分类吗
- firebase - 此用户的凭据对此项目无效,react-native-firebase 中的 confirmResult.confirm(codeInput) 出错
- c# - Windows Forms 数据库使用 LINQ 自动生成 ID 列
- elasticsearch - 如何使用 query_string 查询进行词组前缀搜索
- google-home - Google Actions 智能家居空调机组无法设定温度
- html - 如何在html中分隔表格的列?
- python - 从 Influxdb 查询时是否有大小限制?
- c# - CalendarView StartDateTime 总是在UTC?
- c - C 编程 - 从文件中选择排序(运行失败)