首页 > 解决方案 > Angular Js/Javascript 执行一个函数,直到数组的所有内容都被使用

问题描述

问题是如何将 data["random_code"] 分配给数组中的每个随机代码,但不是一次全部分配。如果 data["random_code"] 没有数组中的值,它将执行 Data.service,如果响应为 200,它将迭代到下一个值并再次执行数据服务,并将等待下一个响应 200,直到数组中的所有值正在使用,然后它将停止。

  let result = me.records.questionaires.map(a => a.random_code);
    var myStringArray = result
    console.log("List of Code", myStringArray)

回应

List of Code (10) ["50-1118561158114", "50-111111118129911", "50-7111851035611", "50-95354410524", "50-2143566173", "50-49361157339", "50-2961010112644", "50-612511266113", "50-8381637318", "50-6819378387"]

交互部分

for (var i = 0; i < arrayLength; i++) {
            data["users"] = me.records.shared_people
            data["random_code"] = myStringArray[i]   
            Data.service(me, data).then(function (response) {
                if (response.status == "200") {

                }
            })


        }

标签: javascriptarraysangularjsloops

解决方案


我更愿意为此使用递归。创建了一种doProcess使用myArrayindex作为参数的方法。doProcess(myArray, 0)使用索引 0 调用。在此函数中调用服务

data["users"] = me.records.shared_people
var myArray = me.records.questionaires

    doProcess(myArray, 0);
    function doProcess(myArray, index) {
      if(myArray.length === index){
           return;
      }
       $scope.random-code = myArray[index].random_code;
       DataService.share(me, data).then(function (response) {
         if (response.status == "200") {
            doProcess(myArray, ++index);
            // process
         }
    });
}

推荐阅读