【问题标题】:How do I make an API call for each result from a sequelize query?如何对 sequelize 查询的每个结果进行 API 调用?
【发布时间】:2019-08-19 13:23:04
【问题描述】:

我有一个 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)
        }),
      )

【问题讨论】:

    标签: node.js api cron sequelize.js


    【解决方案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])
    

    【讨论】:

    • 谢谢,results.map 有效,但它可能比您的解决方案简单得多。 results.map(item => makeAPICall(item.claimId) .then(response => updateDBItemStatus(item.id, response), ))
    • 是的,Micheal,它会更简单,让它更高效,我们可以使用它,因为它不会阻塞每个 id,你可以找到更高效的并使用它。跨度>
    猜你喜欢
    • 1970-01-01
    • 2015-11-30
    • 2023-04-02
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    相关资源
    最近更新 更多