Home > Software design >  problem with making api request in node.js and getting the response in/to function caller
problem with making api request in node.js and getting the response in/to function caller

Time:11-06

Ive spent a bit of time trying to understand this. I hope the answer is obvious and just show my lack of experience

My goal is to send API request to steam for various IDs of game mods and find the time_updated for each one, to put these all into an array and then find out which one most the most recently updated

I have got the code below, but its not quite doing what I want, I think I am just getting muddled over timings

My plan was to have a few different values in arrMODID = [], and to loop through each one, get the time_updated, push that to an array and for const result = await myfunction(); to be able to access the data in the modinfoArray

however that is returning an array with just [{test},{}] in it and is being fired before the function has put any data into the array

can anyone give me a shove in the right direction please

thank you

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();

CodePudding user response:

You need to use an http request library that supports promises so you can await that inside your function. You cannot successfully mix promises and asynchronous operations like request.post() that uses plain callbacks because you can manage the control flow in a promise-like way with plain callbacks.

I'd suggest using the got() library. Also, the request() library has been deprecated and is not recommended for new code. If you absolutely wanted to stay with the request() library, you could use the request-promise module instead, but keep in mind that the request() library is in maintenance mode only (no new feature development) whereas this list of alternatives are all being actively developed.

Here's a runnable implementation using the got() library:

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);
});
  • Related