【问题标题】:Angular Js/ Javascript execute a function until all the content of the array is being usedAngular Js/Javascript 执行一个函数,直到数组的所有内容都被使用
【发布时间】:2019-02-13 08:52:52
【问题描述】:

问题是如何将 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") {

                }
            })


        }

【问题讨论】:

  • 那么,迭代myArray 是否正确?你的代码有什么问题?
  • 我想对每个随机代码执行DataService.share而不重复。
  • 如果有 5 个随机代码,则 DataService.share 将执行 5 次,但只有在响应为 200 时才会迭代到下一个代码
  • 如果我理解错误,请纠正我。您想迭代随机代码并调用DataService.share。如果服务的响应是200,那么只会迭代下一个随机代码,否则将停止迭代。对吗?
  • yes 将迭代到下一个随机代码并再次执行 DataService.share 直到所有元素都是数组,然后它将停止。

标签: javascript arrays angularjs loops


【解决方案1】:

我更愿意为此使用递归。创建了一种方法doProcess,以myArrayindex 作为参数。调用索引为 0 的doProcess(myArray, 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
         }
    });
}

【讨论】:

  • 我已经更新了我的问题,我认为现在已经很清楚了,请先生检查一下,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多