首页 > 解决方案 > Javascript | 在 For 循环之后执行

问题描述

我想在 for 循环动作完成后调用一个函数,请问有什么方向吗?

这是我的代码:

       Function1: function () {
            var $this = this;
            $this.Action();
            var l = $this.list.length;
            for (var i = 0; i < l; i++) {                
            Function2(i)
            }

             function Function2(i){
              axios.post('/api', $this.list[i])          
              .catch(function(error) {
              console.log(error);
              });
             };                     
             },   

我想$this.notAction()什么时候打电话i > l || i == l

标签: javascript

解决方案


使用异步/等待

Function1: async function () {
 var $this = this;
 $this.Action();
 var l = $this.list.length;
 for (var i = 0; i < l; i++) {                
   await Function2(i)
 }
 $this.notAction();

  async function Function2(i){
   try {
    await axios.post('/api', $this.list[i]);
   } catch (err) {
     console.log(err);
   }
  };                     
}

推荐阅读