1

In this err.length code always returns []. Where am I going wrong?

err.length does not wait for map result

router.post('/add', authSigs, async (req, res) => {
  const nds = req.body.nds
  const split = nds.split('\n')
  const err = []

  await split.map(async item => {
    let sub = item.substr(0, 7)
    const checkModel = await modelSerial.findOne({
      'modelNds': sub
    })

    if (!checkModel) err.push(item)
  })

  if (err.length > 0) return res.status(400).send({error: 'Invalid'})
  return res.status(200).send()

})

1 Answer 1

2

You're not awaiting on a Promise, you're doing await [Promise, Promise] so, your await isn't actually waiting for all the promises to resolve, you need to use Promise.all, which takes an array of promises.

The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

const promises =  split.map(async item => {
  let sub = item.substr(0, 7)
  const checkModel = await modelSerial.findOne({
    'modelNds': sub
  })

  if (!checkModel) err.push(item)
});

await Promise.all(promises);
// Now all promises have been resolved
// err will contain items if there were any errors
Sign up to request clarification or add additional context in comments.

2 Comments

Sensational! Let me see if I understood, the promise.all method waits for the resolution of all promises to sequence the code?
Exactly, it will resolve when all the promises pass to it are resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.