迭代数组并进行服务调用并将响应存储在数组中

时间:2017-11-14 10:06:37

标签: javascript ajax

Insert Into try(No, Unixdatetime1, Unixdatetime2, Unixdatetime3 ) Select No, SUBSTRING(...) as Date1, [...] from tspade 是一个数组。我想迭代一个数组并进行服务调用并将响应存储在WordId数组中。

responses

我的服务文件

var wordId = [];
var responses = [];

for (var i = 0; i < result.words.length; i++) {
if (result.words[i].exampleSentences == undefined) {
wordId.push(result.words[i].identifier);
}
}

self.getWordExample(0, wordId, responses, function(responses) {
                console.log(responses);
            });
            console.log("outside",responses);

enter image description here

这是控制台。为什么服务首先执行而wordid正在执行下一步 有没有办法先执行该函数然后返回getWordExample: function(i, wordId, responses,callback) { var self = this; services.WordExampleService.getWordExamples(wordId[i], function(err, response) { responses.push(response); i++; if (wordId[i]) { console.log("wordid",wordId[i]); self.getWordExample(i, wordId, responses); } else if(callback){ console.log(responses); callback(responses); } }); }

1 个答案:

答案 0 :(得分:1)

以递归异步方式调用它:

function callService(wordIdIndex, callback) {
    services.WordExampleService.getWordExamples(wordId[wordIdIndex], function(err, response) {
        responses.push(response);

        wordIdIndex++;
        if (wordId[wordIdIndex]) {
            callService(wordIdIndex);
        }
        else if (callback) {
            callback(responses);
        }
    });
}

 callService(0, function(responses) {
     console.log(responses);
 });

使用此代码代替第二个for语句。

请记住,由于您的请求是异步的,因此依赖于responses的所有内容都应该在该回调中执行。