如何针对序列查询中的每个结果进行API调用?

时间:2019-08-19 04:40:50

标签: node.js api cron sequelize.js

我有一个cron作业,它将查询我的数据库并查找任何状态为“已提交”或“正在处理”的项目,我想对每个项目都进行API调用,以使用外部API,然后使用响应

  const results = await myTable.findAll({
    where: {
      status: {
        [op.or]: [
          'SUBMITTED',
          'PROCESSING'
        ],
      },
    },
  })

我尝试使用forEach,但出现错误“ TypeError:无法读取未定义的属性'Symbol(Symbol.iterator)'”

  await Promise.all(
        results.forEach(async item => {
          makeAPICall(item.id).then(response => updateDBItemStatus(item.id, response)
        }),
      )

1 个答案:

答案 0 :(得分:1)

使用Promise.all从外部api收集所有响应,然后更新数据库。将整个内容包装在异步块中。

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])