如何处理多个异步请求?

时间:2017-08-09 16:44:47

标签: javascript asynchronous

因此,在我的应用中,用户可以上传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永远不会上传。如何改进我的代码?

2 个答案:

答案 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")})

答案 1 :(得分:1)

查看Promise.all - Bluebird是一个很好的承诺图书馆,虽然本土现在也很酷。 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
});