gpt4 book ai didi

node.js - 返回 Async/await 同步 Node

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:47 26 4
gpt4 key购买 nike

在此 err.length 代码中始终返回 []。我哪里出错了?

err.length不等待 map 结果

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

})

最佳答案

您不是在等待Promise,您正在等待[Promise,Promise],因此,您的 wait 实际上并不等待所有的 Promise 得到解析,您需要使用 Promise.all,它接受一个 Promise 数组。

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

关于node.js - 返回 Async/await 同步 Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51212648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com