Node.js承诺和for循环。等待循环内的异步函数

时间:2015-05-30 20:36:58

标签: node.js for-loop promise

我对Node和JS都很陌生。我已经在stackoverflow上阅读了很多内容,并且我认为我个人在我的大脑中有一个在最后几天试图解决这个问题; - )。

此代码的目的是从steam API获取每个播放器的steam名称并将其放入json对象中。之后,json对象用于在网页上显示蒸汽数据。

我开始工作,但是第一次加载网页时它是空的。第二次加载页面时,所有数据都可用。

steam用户ID保存在一个简单的数组中。这个数组被放到一个forEach方法中,在这个方法中,调用steam API来返回每个玩家的名字。此播放器名称将返回到最终的json对象,该对象同时包含蒸汽ID和蒸汽名称。

input = steam ID's from array
process = get steam name from steam ID
output = json object with all steam ID's and names.

重要的是,页面必须等待API调用完成。

我有以下代码:

var cfg = require('config');
var Promise = require('bluebird');


//access steam API for steamId resolution
var Steam = require('steam-webapi');
// Set global Steam API Key
Steam.key = cfg.get('steam.api.key');


// Create a file called STEAM_KEY and stick your API key in it
// (or insert it here)
var steamAPIKey = Steam.key;
if (steamAPIKey.length === 0) {
    try { steamAPIKey = fs.readFileSync('../STEAM_KEY').toString();}
    catch(e) {
        try { steamAPIKey = fs.readFileSync('./STEAM_KEY').toString(); }
        catch(e) { console.log('No API key provided'); }
    }
}


var steamconnect = function() {
    return new Promise(function (resolve, reject) {
        Steam.ready(steamAPIKey, function (err, data) {
            if (err) return console.log(err);
            else {
                var steam = new Steam({key: steamAPIKey});
                resolve(steam);
            }
        });
    });
};


var getsteaminfoforeach = function(arrsid, steam){
    return new Promise(function(resolve, reject){

        dataarr = [];
        var i = 0;

        arrsid.forEach(function(entry, callback) {
            if (entry !== "") {

                getsteaminfo(steam, entry)
                    .then(function(playername) {
                        console.log(playername);
                        dataarr.push({"name": playername, "id": entry});
                        resolve(dataarr);
                    });
            }

        });
    });
};


var getsteaminfo = function(steam, entry) {
    return new Promise(function (resolve, reject) {

        Promise.promisifyAll(Steam.prototype); // Creates an promise wielding function for every method (with Async attached at the end)

        steam.getPlayerSummariesAsync({steamids: entry})
            .then(function (data) {

                playername = data.players[0]["personaname"]; //extract user name from steam user object

                //dataarr.push({"name": playername, "id": entry});

                console.log("get steam user: " + "name: "+playername+ " id: "+ entry);
                resolve(playername);
            });

    });
};


var donext = function() {
    return new Promise(function (resolve, reject) {
        console.log("do next: "+dataarr);
    });
};



arrsid = ["765611980504","765611970371",""];

steamconnect()
    .then(function(steam){
        console.log("arrsid: "+arrsid);

        getsteaminfoforeach(arrsid, steam)
            .then(function (dataarr) {
                console.log("Player name: " + dataarr);
                donext()
        });
    });

这是输出:

arrsid: 765611980504,765611970371,
get steam user: name: steamname1 id: 765611980504
steamname1
Player name: [object Object]
do next: [object Object]
get steam user: name: steamname2 id: 765611970371
steamname2 

我的问题是,steamname ...应该是第一个输出(对于每个steamname),然后执行下一个:[]必须被调用。

我确定有一个简单的解决方案。非常感谢你!

0 个答案:

没有答案