2017-08-09 212 views
1

因此,在我的應用程序中,用戶可以上傳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永遠不會上傳。我如何改進我的代碼?

+0

這已經在這裏問了很多,請搜索有關異步javascript和你會看到答案,衆說紛紜。簡而言之,使用此:https://caolan.github.io/async/ – Graham

+0

請參閱該解決方案:https://stackoverflow.com/questions/13912775/jquery-deferred-getting-result-of-chained-ajax -alls/13913059#13913059 – Zim84

+0

[Async JavaScript Callback]的可能重複(https://stackoverflow.com/questions/27864294/async-javascript-callback) – Graham

回答

1

退房Promise.all - 藍鳥是許諾一個好的圖書館,雖然本土完全是太酷了。 http://bluebirdjs.com/docs/api/promise.all.html

會是這個樣子:

var p = []; 

if (img1) p.push(uploadImg(img1...)); 
if (img2) p.push(uploadImg(img2...)); 
if (img3) p.push(uploadImg(img3...)); 

return Promise.all(p).then(function() { 
    // redirection here 
}); 
+0

非常感謝! –

2

您可以使用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")}) 
+0

Promise.all原生於JS嗎?沒有圖書館? @jdubjdub提到bluebirdJS。 –

+1

Promise.all原生於JS。 https://developers.google.com/web/fundamentals/getting-started/primers/promises – Ripon