2017-08-09 213 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