【问题标题】:Handle errors with parallel async requests使用并行异步请求处理错误
【发布时间】:2019-05-13 05:15:56
【问题描述】:

我有 6 个异步请求。如果其中一个出错,返回 404,其他请求也不起作用。我使用async.parallel 提出这些请求。当其中一个请求失败时,我正在尝试提出其他请求。但我做不到。

这是我的代码:

    async.parallel({
      request1: async (callback) => {
        const [err, result] = await to(this.$store.dispatch('myAction1', {
          id: this.$route.params.id,
        }));
        callback(err, result);
      },
      request2: async (callback) => {
        const [err, result] = await to(this.$store.dispatch('myAction2', {
          params: {
            id: this.$route.params.id,
            page: this.page,
            size: this.size,
          },
        }));
        callback(err, result);
      },
      request3: async (callback) => {
        const [err, result] = await to(this.$store.dispatch('myAction3', {
          data: {
            filters: this.inputs.filters,
            projections: this.inputs.projections,
            showTotalCount: this.inputs.showTotalCount,
          },
          params: {
            page: this.page,
            size: this.size,
          },
        }));
        callback(err, result);
      },
      request4: async (callback) => {
        const [err, result] = await to(this.$store.dispatch('myAction4'));
        callback(err, result);
      },
      request5: async (callback) => {
        const [err, result] = await to(this.$store.dispatch('myAction5', {
          id: this.$route.params.id,
        }));
        callback(err, result);
      },
      request6: async (callback) => {
        const [err, result] = await to(this.$store.dispatch('myAction6', {
          params: {
            id: this.$route.params.id,
          },
        }));
        callback(err, result);
      },
    }, (err, results) => {
      if (err) {
        // Show error message when one of them fails
      }
      // doing something when all requests success and hide the page loader.
      this.hidePageLoader();
    });

如果这些请求中的一个返回 404,则此代码始终显示页面加载器,我想将失败的请求作为 null 传递给我的 results 对象或返回其他结果,而 results 对象中的请求没有失败。我怎样才能使它正确

【问题讨论】:

    标签: javascript ajax asynchronous vue.js request


    【解决方案1】:

    为了让其他任务继续处理,即使其他任务失败,您需要将任务推送到一个数组,其中每个任务都包含在async.reflect 中,并将任务数组设置为@987654323 的第一个参数@。

    例如:

    async.parallel([
     async.reflect((callback) => {
       return callback(null, "one");
     }),
     async.reflect((callback) => {
       return callback("error");
     }),
     // another tasks
    ], function(error, results) {
      if(error)
        return cb(error)
    
      // results[0].value ->> "one"
      // results[1].error ->> "error"
    
      return cb(results)
    })
    

    来源:Async Documentationutils>>reflect

    【讨论】:

      猜你喜欢
      • 2017-12-26
      • 2021-11-04
      • 2018-03-28
      • 1970-01-01
      • 2013-03-20
      • 2019-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多