繁体   English   中英

异步/等待-带有对象映射功能的承诺

[英]Async / Await - Promise with Object map function

我真的很困惑 我尝试了很多事情,但无法达到正确的结果。

这是场景; 我有可以选择多种产品并一一删除的产品清单。 我要等所有项目都可以删除,然后再给我数一次。

async delete (ids) {

    const res = await this.deleteProcess(ids);
    return res;

  },

  deleteProcess(ids) {

    let countS = 0;

    Object.assign(ids).map((id) => {

      axios({
        method: "DELETE",
        url: store.getters.getServerPath + "api/v1/product/" + id,
        headers: store.getters.getConfigHeaders,
        withCredentials: true
      }).then(function (response) {

        countS++;

      }).then(() => {

        console.log(countS);
        return countS;
      });

    });
  }

并按以下方式调用此函数:

deleteSelected (id) {
                if (id !== undefined) {
                    this.selectedRows.push(id);
                }
                controller.delete(this.selectedRows).then(function (res) {

                    alert(res + " items deleted");
                });
            },

结果res总是返回undefined 但是在deleteProcess console.log内部显示了删除了多少个项目。

您应该改用Promise.all ,每次返回响应时都增加countS

deleteProcess(ids) {
  let countS = 0;
  return Promise.all(ids.map((id) => (
    axios({
      method: "DELETE",
      url: store.getters.getServerPath + "api/v1/product/" + id,
      headers: store.getters.getConfigHeaders,
      withCredentials: true
    }).then(function (response) {
      countS++;
    })
  )))
  .then(() => countS);
}

但是您也可以只计算idslength ,而不要保留一个外部countS变量:

.then(() => ids.length);

另请注意

Object.assign(ids)

什么都不做-结果表达式是原始ids变量=== ,所以最好也使用原始变量。

您还可以考虑在发生问题时添加catch

controller.delete(this.selectedRows)
  .then(function (res) {
    console.log(res + " items deleted");
  })
  .catch((err) => {
    console.log('error', err);
  });

您的deleteProcess方法不返回任何内容,因此res是未定义的。 如果您想要完全使用异步/等待模式的代码,并一一删除它们,则可以执行以下操作:

async deleteProcess(ids) {
  let countSuccess = 0;
  let countFailure = 0;
  for (const id of ids) {
     try {
       await axios({
         method: "DELETE",
         url: store.getters.getServerPath + "api/v1/product/" + id,
         headers: store.getters.getConfigHeaders,
         withCredentials: true
       });
       countSuccess++;
      } catch (error) {
       countFailure++;
      }
  }
  return countSuccess;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM