gpt4 book ai didi

javascript - 在异步代码的 for 循环完成后,如何解决这个 promise ?

转载 作者:行者123 更新时间:2023-12-03 01:27:53 26 4
gpt4 key购买 nike

似乎无法弄清楚如何在没有 setTimeout 的情况下完成这项工作。我想仅在异步 PostgreSQL 内容完成并且映射包含应有的所有键/值对后才控制台记录我的映射。

const map = new Map();
pool.query(`SELECT * FROM trips WHERE destination = $1 AND begin_time >= $2 AND begin_time < $3 ORDER BY begin_time`, ['BROWNSVILLE ROCKAWAY AV', '2018-07-18 00:00-04:00', '2018-07-19 00:00-04:00'])
.then(res => {
return new Promise((resolve, reject) => {
const { rows } = res;
resolve(rows);
});
})
.then(res1 => {
return new Promise((resolve, reject) => {
for (let i = 0; i < res1.length; i++) {
if (res1[i + 1]) {
pool.query(`SELECT * FROM get_hwtable($1, $2)`, [res1[i].trip_id, res1[i + 1].trip_id]).then(res => {
const { rows: hwRows } = res;
map.set([res1[i].trip_id, res1[i + 1].trip_id], hwRows);
}).catch(e => console.log('20', e));
}
}
setTimeout(() => {
resolve(map);
}, 8000);
});
})
.catch(e => console.log('25', e))
.finally(function () {
console.log(map);
});

最佳答案

您可以简单地对 pool.query 返回的 promise 数组使用 Promise.all

const map = new Map();
pool.query(`SELECT * FROM trips WHERE destination = $1 AND begin_time >= $2 AND begin_time < $3 ORDER BY begin_time`, ['BROWNSVILLE ROCKAWAY AV', '2018-07-18 00:00-04:00', '2018-07-19 00:00-04:00'])
.then(({rows}) => rows)
.then(res1 => Promise.all(res1.map((r, i) => {
if (res1[i + 1]) {
return pool.query(`SELECT * FROM get_hwtable($1, $2)`, [r.trip_id, res1[i + 1].trip_id])
.then(res => {
const { rows: hwRows } = res;
map.set([res1[i].trip_id, res1[i + 1].trip_id], hwRows);
}).catch(e => console.log('20', e))
}
})))
.catch(e => console.log('25', e))
.finally(function () {
console.log(map);
});

关于javascript - 在异步代码的 for 循环完成后,如何解决这个 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51438805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com