首页 > 解决方案 > 在 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();

标签: node.js

解决方案


您需要使用支持 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);
});

推荐阅读