gpt4 book ai didi

javascript - Promise 无法通过异步得到解决

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:03 27 4
gpt4 key购买 nike

我正在使用 igmur api 上传图像。我使用 Promises、async-await 在 Node.js 中编写了一个应用程序。 (请注意,我对这些概念还很陌生)。

我的代码似乎确实有效。它将图像上传到 igmur。但问题是, promise 并没有得到解决。请引用下面的代码。

router.post('/images/upload', async (req, res) => {
/* we would receive a request of file paths as array */
let filePaths = req.body.urls;

let multipleUpload = new Promise(async (resolve, reject) => {
let upload_len = filePaths.length,
upload_res = new Array();

for (let i = 0; i <= upload_len + 1; i++) {
let filePath = filePaths[i];
await imgur.upload(filePath, (error, result) => {
console.log(" A -> ");
if (upload_res.length === upload_len) {
console.log("******");
/* resolve promise after upload is complete */
resolve(upload_res)
} else if (result) {
/*push public_ids in an array */
console.log("OK")
upload_res.push(result.public_id);
} else if (error) {
console.log(error)
reject(error)
}

})

}
})
.then((result) => console.log(result))
.catch((error) => error)

let upload = await multipleUpload;
res.json({
'response': upload
})
})

我关注了这个tutorial ,它做了类似的事情。

最佳答案

我至少看到两个问题:

  • 在不需要时将异步与 Promise 混合使用
  • 我怀疑 imgur.upload 没有返回 Promise,因为它接受回调函数。

我认为这应该解决它:

router.post('/images/upload', async (req, res) => {
let filePaths = req.body.urls
let upload_len = filePaths.length
let multipleUpload = filePaths.map(filePath => {
return new Promise((resolve, reject) => {
imgur.upload(filePath, (err, result) => {
if (err) {
reject(err)
} else {
resolve(result.public_id)
}
})
})
})

let upload = await Promise.all(multipleUpload)

res.json({
response: upload,
})
})

关于javascript - Promise 无法通过异步得到解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52802932/

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