因此,在我的應用程序中,用戶可以上傳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