gpt4 book ai didi

javascript - Promise.all 返回未定义

转载 作者:行者123 更新时间:2023-12-02 23:27:23 25 4
gpt4 key购买 nike

当我异步映射一个数组时,Promise.all 应该让函数等待,直到所有的 promise 都得到解决。但是,Promise.all 显示为未定义。这是我的代码。请有人告诉我我做错了什么?谢谢。

router.get("/vehicle_reports/interior-pictures", auth, async (req, res) => {

const fileKeysObj = await Report.findOne({ orderId: req.params.jobId }, {
"vehicleInterior": 1
})
const fileKeysArray = fileKeysObj.interior
console.log("fileKeysArray: ", fileKeysArray);

//Retrieve the files from S3
const files = fileKeysArray.map(async (item) => {
const params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: item.fileKey
}
await s3.getObject(params, async (err, data) => {
if (err) {
throw new Error()
}
else {
const base64Data = base64Arraybuffer.encode(data.Body)
const contentType = data.ContentType
const fileName = item.fileName
return { base64Data, contentType, fileName }
}
})
})
console.log( files) //Pending promise
await Promise.all(files)
console.log( files) //Undefined
res.send(files) //Sends empty array
})

最佳答案

我希望人们停止炒作async/awaitawait 关键字旨在与 Promise 配合使用。并且并非所有异步函数都会返回 Promise。许多 API(例如 S3)都使用回调。此外,您可以期望返回多个/无限数据的架构(例如服务器监听传入连接或读取流)不太适合基本上是单次的 Promise。对于那些EventEmitters 来说更合适。

async 关键字不会将函数转换为 Promise。它确实返回一个 Promise,但无法将基于回调的函数转换为可与 await 一起使用的 Promise。为此,您需要使用原始的 Promise 构造函数。因此,获取promise数组的正确方法如下:

const files = fileKeysArray.map((item) => { /* note: async keyword is useless here */
const params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: item.fileKey
}


// We are returning a Promise, so no need to force it to further
// return a promise by marking this function as "async" above:

return new Promise((perfectly_fine, oops_something_went_wrong) => {
s3.getObject(params, async (err, data) => {
if (err) {
// Normally people would name this function "reject"
// but I'm illustrating that the name is really up to you
// and is not part of the syntax:

oops_something_went_wrong(err)
}
else {
const base64Data = base64Arraybuffer.encode(data.Body)
const contentType = data.ContentType
const fileName = item.fileName

// This is how you "return" to a promise:

perfectly_fine({ base64Data, contentType, fileName })
}
})
})
})

现在您可以等待结果了。但是您使用 await 是错误的。 await的正确方法如下:

let resulting_files = await Promise.all(files);
console.log(resulting_files);

您也可以选择不使用await。相反,您可以使用 .then():

Promise.all(files).then(resulting_files => {
// use resulting_files here:

console.log(resulting_files);
});

关于javascript - Promise.all 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56677707/

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