Michael
Michael

Reputation: 405

How do I make an API call for each result from a sequelize query?

I have a cron job which will query my database and find any items that have a status of 'SUBMITTED' or 'PROCESSING' for each of which I want to make an API call to an external API and then update the database with the response

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

I tried using a forEach but that gave the error "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)
        }),
      )

Upvotes: 1

Views: 551

Answers (1)

Nayan Patel
Nayan Patel

Reputation: 1761

Collecting all the responses from the external api using Promise.all and then updating the db. Wrap the whole thing in a async 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])

Upvotes: 1

Related Questions