我有一个 cron 作业,它将查询我的数据库并查找状态为“已提交”或“正在处理”的任何项目,对于每个项目,我想对外部 API 进行 API 调用,然后使用响应更新数据库
const results = await myTable.findAll({
where: {
status: {
[op.or]: [
'SUBMITTED',
'PROCESSING'
],
},
},
})
我尝试使用 forEach 但出现错误“TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined”
await Promise.all(
results.forEach(async item => {
makeAPICall(item.id).then(response => updateDBItemStatus(item.id, response)
}),
)
最佳答案
使用 Promise.all 从外部 api 收集所有响应,然后更新数据库。将整个事情包装在一个异步 block 中。
let api_call_array = results.map( item => makeAPICall(item.id));
const api_response = await Promise.all([api_call_array])
let update_db_item = api_response.map((response, index)=> {
return updateDBItemStatus(results[index].item.id, response)
})
const update_response = await Promise.all([update_db_item])
关于node.js - 如何对sequelize 查询的每个结果进行API 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57550573/