循环中的异步函数 - Vue.js

时间:2021-07-30 14:41:14

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

我在 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;
   }

1 个答案:

答案 0 :(得分:0)

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

// 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;
  });
}