【问题标题】:Async function in loop - Vue.js循环中的异步函数 - Vue.js
【发布时间】:2021-07-30 23:49:11
【问题描述】:

我在 vue.js 工作。在我的代码中,我尝试在循环中调用 2 个方法,但我希望第二种方法异步运行。 第一种方法调用 API 来更新数据库。第二种方法调用 API 来运行工作流,这个方法在文件上进行更新。不可能在同一个文件上启动多个工作流。 我想等到第二种方法的结果再继续。

class SessionFormationService {
  async UpdateBesoin(
    besoinId: number,
    eventId: number,
    nouveauStatutCode: string,
    prioriteBesoin: string
  ) {
    const url = XXX;
    const result = await axiosApp(url, { ...option, method: "patch" });
    return result.data.sessionFormation as SessionFormation[];
  }
}

export const sessionFormationService = new SessionFormationService();

运行工作流程:

class WorkflowService {
  async updateXml(
    fichierXML: string,
    activityId: number,
    axe: string,
    priority: string,
    bookingId: string,
    bookingVersionNumber: string,
    statutName: string
  ){

    const data = "XXX";
    const xmls ="XXX";
      
    return await axios.post(
      "URL",
      xmls,
      {
        headers: {
          XXX
        }
      }
    )
  }
}
export const workflowService = new WorkflowService();
 

还有我的应用:

   validerModification: function() {
     const rows = this.updateRow;
     rows.map(element => {  
         sessionFormationService.UpdateBesoin(
         element.bookingId,
         element.eventId,
         "02",
         element.priorite
       );
         workflowService
         .updateXml(
           element.urlPif,
           element.activityId,
           element.axe,
           element.priorite, 
           element.bookingId,
           "02",
           element.statut
         ); 
     });

     this.updateRow.length = 0;
     rows.length = 0;
   }

【问题讨论】:

    标签: javascript vue.js asynchronous async-await axios


    【解决方案1】:

    您可以在async 函数的简单循环中使用await

    // You should probably move this to a service too to keep your component lean and dry.
    
    async function validerModification(rows) {
      for (const element of rows) {
        await sessionFormationService.UpdateBesoin(
          // ...
        );
        await workflowService.updateXml(
          // ...
        );
      }
    }
    

    组件:

    validerModification: function() {
       validerModification(this.updateRow).then(function(){
            this.updateRow.length = 0;
      });
    }
    

    【讨论】:

    • 很好,这个解决方案有效。非常感谢;)
    猜你喜欢
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    相关资源
    最近更新 更多