因此,在我的应用程序中,用户可以上传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永远不会上传。我如何改进我的代码?
这已经在这里问了很多,请搜索有关异步javascript和你会看到答案,众说纷纭。简而言之,使用此:https://caolan.github.io/async/ – Graham
请参阅该解决方案:https://stackoverflow.com/questions/13912775/jquery-deferred-getting-result-of-chained-ajax -alls/13913059#13913059 – Zim84
[Async JavaScript Callback]的可能重复(https://stackoverflow.com/questions/27864294/async-javascript-callback) – Graham