node.js - 在 node.js 中发出 api 请求并在函数调用者中获取响应的问题
问题描述
我花了一些时间试图理解这一点。我希望答案是显而易见的,只是表明我缺乏经验
我的目标是向 Steam 发送 API 请求以获取各种游戏模组 ID,并为每个模组找到 time_updated,将它们全部放入一个数组中,然后找出最近更新的那个
我有下面的代码,但它并没有完全按照我的意愿去做,我想我只是对时间感到困惑
我的计划是在 arrMODID = [] 中有几个不同的值,然后循环遍历每个值,获取 time_updated,将其推送到数组中,const result = await myfunction();
以便能够访问modinfoArray
然而,这只是返回一个数组,[{test},{}]
并且在函数将任何数据放入数组之前被触发
谁能给我一个正确的方向
谢谢你
import request from 'request';
const myfunction = async function(x, y) {
var arrMODID = ["2016338122"];
var modinfoArray = []
var timeUpdated
for (const element of arrMODID) {
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1',
body: 'itemcount=1&publishedfileids[0]=2016338122',
},
function(error, response, body){
var response = JSON.parse(body);
var myResponse = response.response.publishedfiledetails
myResponse.forEach(function(arrayItem) {
//console.log(arrayItem.time_updated)
timeUpdated = arrayItem.time_updated
//console.log(timeUpdated)
modinfoArray.push({"2016338122":arrayItem.time_updated})
console.log(modinfoArray) // only this log returns the added items
})
});
}
return ["test", modinfoArray];
};
// Start function
const start = async function(a, b) {
const result = await myfunction();
console.log(result); // this returns the empty array
}
// Call start
start();
解决方案
您需要使用支持 Promise 的 http 请求库,以便您可以await
在函数中使用它。您无法成功地混合使用普通回调的 Promise 和异步操作request.post()
,因为您可以使用普通回调以类似 Promise 的方式管理控制流。
我建议使用got()
图书馆。此外,该request()
库已被弃用,不推荐用于新代码。如果您绝对想继续使用该request()
库,则可以改用该request-promise
模块,但请记住该request()
库仅处于维护模式(没有新功能开发),而此替代列表都在积极开发中。
这是使用该got()
库的可运行实现:
import got from 'got';
const myfunction = async function() {
const arrMODID = ["2016338122"];
const modinfoArray = [];
for (const element of arrMODID) {
const response = await got.post({
headers: { 'content-type': 'application/x-www-form-urlencoded' },
url: 'http://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1',
body: 'itemcount=1&publishedfileids[0]=2016338122',
}).json();
const myResponse = response.response.publishedfiledetails;
for (const arrayItem of myResponse) {
modinfoArray.push({ "2016338122": arrayItem.time_updated });
}
}
return ["test", modinfoArray];
};
// Start function
const start = async function() {
const result = await myfunction();
console.log(result);
return result;
}
// Call start
start().then(result => {
console.log("done");
}).catch(err => {
console.log(err);
});
推荐阅读
- facebook - 使用 Facebook API 的用户到用户消息传递
- flask - 如何在烧瓶中的现有表中添加一列
- javascript - Chartjs 2.7.3:在正确的 X 位置轴上设置 Y 数据
- azure - 通过 Intellij 部署 Azure 函数应用
- android - 从 DialogFragment 访问宿主 Activity 的视图
- node.js - 如何调试 websocket 客户端丢失连接并重新建立它
- swift - 如何定位作为子视图添加到视图子视图的 tableView
- javascript - 如何呈现从firebase检索到的列表
- php - Laravel Cookie::get 返回 null
- mysql - 在 phpmyadmin SQL 选项卡上使用 IF 语句