简体   繁体   English

等待调用函数完成,然后再进行迭代

[英]Waiting for a call function to finish before iterating forward

I am in a bit of a bind here regarding a code I have to write. 对于我必须编写的代码,我有点束缚。 At the moment I am trying to iterate through an array of strings. 目前,我正在尝试遍历字符串数组。 After a certain text is found, if a value is true, the value is bound to a temporaryObject.img. 找到特定文本后,如果值是true,则该值绑定到一个临时对象.img。 After that a call has to be made to the server in order for some information to be retrieved and to be bound to the same temporaryObject as a second property (temporaryObject.url). 之后,必须对服务器进行调用,以便检索某些信息并将其绑定到与第二个属性(temporaryObject.url)相同的临时对象。 Unfortunately, the call is resolved probably after the iteration is done because it does not add this add the url from the call to the server in the Object. 不幸的是,调用可能在迭代完成后得以解决,因为它没有添加此内容,因此将调用中的URL添加到对象中的服务器。 The libraries I am using are angularjs and jquery. 我正在使用的库是angularjs和jquery。

Here is a part of the code I wrote. 这是我编写的代码的一部分。

$scope.Data = [];
var strArray = ["img1", "link", "img2", "link2", "img3", "link3"];
var re1 = /<img/;
for(var i = 0 ; i < strArray.length ; i++) {
    var tempObject = {};
    var test = re1.test(strArray[i]);
    if (test){
    tempObject.img = strArray[i + 1];
    myAngularService.getServerInformation().then(function(result){
        tempObject.url = result;
        $scope.Data.push(tempObject);
    }
   }

Unfortunately, the information from the server does not arrive in the same time as the iteration is done or something goes wrong since $scope.Data will not contain the url requested from the server. 不幸的是,由于$ scope.Data将不包含服务器请求的url,因此服务器发出的信息不会在迭代完成的同时到达,否则会出错。 Any suggestions as how to use maybe a promise for this kind of code would be appreciated. 任何有关如何使用此类代码的建议都将不胜感激。 I tried searching every possible solution but with no avail. 我尝试搜索所有可能的解决方案,但无济于事。

Javascript is function-scoped. Javascript是功能范围的。 In other words: 换一种说法:

if (true) {
    var testing = 5;
}
console.log(testing); // Logs 5

Applying this to your example, tempObject in your .then callback function are all referencing the same variable! 应用到您的示例, tempObject在你的.then回调函数都引用相同的变量!

One solution is to use an Immediately-Invoked Function Expression (IIFE) inside your for statement to create a new scope: 一种解决方案是在for语句中使用立即调用函数表达式(IIFE)来创建新范围:

for(var i = 0 ; i < strArray.length ; i++) {
    (function() {
        var tempObject = {}; // Is now declared within the new function
        /* ... code here ... */
    })();
}

Another solution is to simply use $.each (or angular.forEach ): 另一种解决方案是简单地使用$.each (或angular.forEach ):

$.each(strArray, function(index, value) {
    var tempObject = {}; // Is now declared within the new function
    /* ... code here ... */
}); 

Regarding waiting for all your calls to finish, one solution is to store your promises in an array use angular's $q service: 关于等待所有呼叫完成,一种解决方案是使用angular的$ q服务将您的诺言存储在数组中:

$scope.Data = [];
var promises = [];
var strArray = ["img1", "link", "img2", "link2", "img3", "link3"];
var re1 = /img/;
$.each(strArray, function (index, value) {
    var tempObject = {};
    var test = re1.test(value);
    if (test) {
        tempObject.img = strArray[index + 1];

        var myPromise = myAngularService.getServerInformation();

        myPromise.then(function (result) {
            tempObject.url = result;
            $scope.Data.push(tempObject);
        }

        promises.push(myPromise);
    }
})

$q.all(promises).then(function() {
    // All calls will have finished
    console.log($scope.Data); 
}, function() {
    // At least 1 call failed!
    console.log("an error occurred!");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM