Reputation: 51
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()
})
Upvotes: 1
Views: 61
Reputation: 40444
You're not await
ing 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
Upvotes: 2