分享

javascript – 节点js for-loop在下一次迭代之前等待异步函数?

 印度阿三17 2019-10-02

我正在创建一个每隔一段时间刷新一次数据的函数,而且我遇到了我的请求链问题.问题是我有一个for循环运行异步请求,for循环将在请求完成之前完成.

setInterval(function(){ // this updates the total hours of all members every 10 seconds
    request({ // this gets all of the loyalty program members
        url: "",//omitted
        method: "GET"
    },
        function(listError, listResponse, listBody) {
            if(listError == null && listResponse.statusCode == 200) {
                var varBody = {};
                var listObj = JSON.parse(listBody);
                for(var i = 0; i < listObj.result.length; i  ) { // parses through all of the members to update their hours

                    console.log(i);//****PRINT STATEMENT

                    varBody.index = i;
                    varBody.memberID = listObj.result[i].program_member.id;
                    request({ //we do this request to get the steam ID of the program member
                            url: "",//omitted
                            method: "GET"
                        },
                        function(fanError, fanResponse, fanBody) {

                            var fan = JSON.parse(fanBody);
                            if(fanError == null && fanResponse.statusCode == 200 && fan.result.profiles.length != 0) { // make sure that the profile isn't empty
                                request({
                                        url:"",//omitted
                                        method: "GET"
                                    },
                                    function(hourError, hourResponse, hourBody) {
                                        if (hourError == null && hourResponse.statusCode == 200) {
                                            var gameList = JSON.parse(hourBody);
                                            var minutes = 0;
                                            for (var j = 0; j < gameList.response.games.length; j  ) { // for loop to calculate the minutes each user has on steam
                                                minutes  = gameList.response.games[j].playtime_forever;
                                            }
                                            var deltaHours = 1;
                                            if(deltaHours != 0) {
                                                var transaction = { // updated member object to be inserted
                                                    pointsearned: deltaHours,
                                                    pointsused: 0,
                                                    loyaltyprogram_id: loyaltyID,
                                                    programmember_id: memberID
                                                };
                                                request({ // POST request to update the member
                                                        url: "",//omitted
                                                        method: "POST",
                                                        body: JSON.stringify(transaction),
                                                        headers: {
                                                            "Content-Type": "application/json"
                                                        }
                                                    },
                                                    function(updateError, updateRes, updateBody) {
                                                        if(updateError == null && updateRes.statusCode == 200) {
                                                            console.log("Success");//****PRINT STATEMENT
                                                        }
                                                    }
                                                );
                                            }
                                        }
                                    }
                                );
                            }
                        }
                    );
                }
            }
            console.log("Users Updated"); //****PRINT STATEMENT
        }
    );
}, 10000);

如果我要运行此代码,它将打印:

0
1
2
3
Success
Success
Success
Success

我知道问题是什么.事实是for循环不等待请求完成.我不知道的是解决这个问题.有没有人有任何想法?

解决方法:

你想要async库.

例如,

for(var i = 0; i < listObj.result.length; i  ) {
    varBody.index = i;
    varBody.memberID = listObj.result[i].program_member.id;
    request(
        ...
    , function () {
        // Do more Stuff
    });
}

可以这样写:

async.forEachOf(listObj.result, function (result, i, callback) {
    varBody.index = i;
    varBody.memberID = result.program_member.id;
    request(
        ...
    , function () {
        // Do more Stuff
        // The next iteration WON'T START until callback is called
        callback();
    });
}, function () {
    // We're done looping in this function!
});

在异步中有很多方便的实用程序函数,这使得回调更容易.

来源:https://www./content-1-480351.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多