【问题标题】:How to handle multiple async requests?如何处理多个异步请求?
【发布时间】:2017-08-09 16:44:47
【问题描述】:

所以在我的应用中,用户可以上传 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 asynchronous


【解决方案1】:

你可以使用 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")})

【讨论】:

【解决方案2】:

查看 Promise.all - Bluebird 是一个很好的 promise 库,尽管 native 现在也很酷。 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
});

【讨论】: