)
我正在开发node.js表达自定义API项目。 目前我在尝试推送数据时遇到问题...
这是我的代码:
module.exports = function(config, steamClient, csgo, database, teamspeakClient, router) {
var async = require('async'),
apicache = require('apicache'),
cache = apicache.middleware,
mysql = require('mysql');
async.waterfall([
function(callback) {
router.get('/CsgoUser/requestPlayersProfile/v1/:steamids', function(req, res) {
var steamids = req.params.steamids.split(',');
var csgo_data = [];
steamClient.getPersonas(steamids, function(resp) {
Object.keys(resp).forEach(function (steamid){
if (!steamClient.myFriends.hasOwnProperty(steamid)) {
if (resp[steamid].game_played_app_id == 730) {
csgo.requestPlayersProfile(steamid, function(result) {
console.log(result);
csgo_data.push(csgo_data, {steamid: steamid, response: result});
});
}else{
csgo_data.push({steamid: steamid, response: steamid + " is not playing csgo"});
}
}else{
csgo_data.push({steamid: steamid, response: steamid + " Is not bot´s friend..."});
}
});
res.json({ success: true, code: 200, response: csgo_data });
});
});
}
])};
结果如下:
{“success”:true,“code”:200,“response”:[{“steamid”:“76561198013250658”,“response”:“76561198013250658不是博特的朋友......”},{“ steamid“:”76561198263874163“,”“”:“76561198263874163不是博特的朋友......”},{“steamid”:“76561198156967342”,“回复”:“76561198156967342不是博特的朋友......” }]}
调用
时出现问题csgo.requestPlayersProfile(steamid, function(result) {
console.log(result);
csgo_data.push(csgo_data, {steamid: steamid, response: result});});
console.log的输出数据(例如:{“ID”:“hello”})在终端上正确显示,但它没有被推送到csgo_data数组......
请尽量给我一个解释: - )
答案 0 :(得分:1)
至于我要避免这种类型的问题,试着在Promises上重写forEach(..)
。像这样:
steamClient.getPersonas(steamids, function(resp) {
Promise.all(Object.keys(resp).map(
(steamid)=>new Promise((resolve)=>{
if (!steamClient.myFriends.hasOwnProperty(steamid)) {
if (resp[steamid].game_played_app_id == 730) {
csgo.requestPlayersProfile(steamid, (result)=> {
console.log(result);
resolve({steamid: steamid, response: result});
});
}else{
resolve({steamid: steamid, response: steamid + " is not playing csgo"});
}
}else{
resolve({steamid: steamid, response: steamid + " Is not bot´s friend..."});
}
})
)
).then((csgo_data)=>
res.json({ success: true, code: 200, response: csgo_data })
);
});
答案 1 :(得分:1)
这是我的Promisified版本:
// build Promise from steamid
function getData(steamid) {
return new Promise((resolve, reject) => {
var data = {
steamid: steamid,
response: steamid + " Is not bot's friend..."
};
if (!steamClient.myFriends.hasOwnProperty(steamid)) resolve(data);
else if (resp[steamid].game_played_app_id != 730) {
data.response = steamid + " is not playing csgo";
resolve(data);
} else {
csgo.requestPlayersProfile(steamid, function(result) {
console.log(result);
data.response = result;
resolve(data);
});
}
});
}
// build array of promises and pass to Promise.all()
Promise.all(Object.keys(resp).map(steamid => getData(steamid)))
.then(data => {
res.json({
success: true,
code: 200,
response: csgo_data
});
});