gpt4 book ai didi

javascript - 如何处理多个异步请求?

转载 作者:行者123 更新时间:2023-11-30 11:32:57 26 4
gpt4 key购买 nike

所以在我的应用中,用户可以上传 1 到 3 张图片,当他点击保存按钮时,我将它们上传到 firebase。

到目前为止,这是我的代码,我知道它很糟糕,我正在寻找一种使其高效的方法。

    if (img1) {
uploadImage(img1, 'image/jpeg', 'imageOne', uuid)
.then(() => {
console.log('Image 1 was uploaded succesfully');

}).catch(err => console.log(err));
}

if (img2) {
uploadImage(img2, 'image/jpeg', 'imageTwo', uuid)
.then(() => {
console.log('Image 2 was uploaded succesfully');

}).catch(err => console.log(err));
}

if (img3) {
console.log('there is img3')
uploadImage(img3, 'image/jpeg', 'imageThree', uuid)
.then(() => {
console.log('Image 3 was uploaded succesfully');

}).catch(err => console.log(err));
}

问题是我想在上传完成后将用户重定向到主页。但是很难决定重定向代码应该放在哪里。

我考虑过像这样嵌套 if 语句:

if (img1) {
uploadImage(img1, 'image/jpeg', 'imageOne', uuid)
.then(() => {
console.log('Image 1 was uploaded succesfully');

if (img2) {
uploadImage(img2, 'image/jpeg', 'imageTwo', uuid)
.then(() => {
console.log('Image 2 was uploaded succesfully');

}).catch(err => console.log(err));
}


}).catch(err => console.log(err));
}

但是如果用户只上传了 img2 而不是 img1 呢?那么 img2 将永远不会被上传。我怎样才能改进我的代码?

最佳答案

你可以使用 Promise.all

let promises = [];
if (img1) {
promises.push(uploadImage(img1, 'image/jpeg', 'imageOne', uuid);
}
if (img2) {
promises.push(uploadImage(img2, 'image/jpeg', 'imageTwo', uuid);
}

// etc...

Promise.all(promises).then(() => {console.log("All requests are done")})

关于javascript - 如何处理多个异步请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45596384/

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