javascript - Node js for循环在下一次迭代之前等待异步函数?

标签 javascript node.js npm-request

我正在制作一个经常刷新数据的函数,但我的请求链存在问题。问题是我有一个运行异步请求的 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 循环不会等待请求完成。我不知道的是解决这个问题。有人有什么想法吗?

最佳答案

为了完整起见,“手动”顺序执行异步操作的方法是使用递归:

function dothings(things, ondone){
    function go(i){
        if (i >= things.length) {
            ondone();
        } else {
            dothing(things[i], function(result){
                return go(i+1);
            });
        }
    }
    go(0);
}

关于javascript - Node js for循环在下一次迭代之前等待异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38773912/

相关文章:

javascript - 在 jquery 中准备好 $.mobile.changePage 后如何运行回调函数?

javascript - 切换多个类

javascript - 如何为 highcharts 创建 Json 格式的数据

html - 在 Node JS 中登录后/favicon.ico

javascript - 如何为 node.js 请求库设置超时回调?

javascript - 有条件的 promise 链

javascript - 使用 javascript 或 jquery 禁用鼠标双击

javascript - NodeJS 上传图片卡住了

javascript - Protractor 中显示失败 401 未经授权错误

javascript - 无法在 Node js中安装强大的