Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get async/await to wait for my nested array to fill

I am having an issue where I can see the array and the data of "arrayOfResults", but when I try to access a certain part of the array, it says undefined. I know it has something to do with the asynchronous call because if I put console.log on a timeout it displays correctly. I'm pretty new to async calls in general, let alone awaits. Thanks for the help!

async function convertToCSV() {
        var userInput = document.getElementById("thing").value; //value from text area
        var arrayOfUserInput = userInput.split('\n').map(str => str.replace(/\s/g, '')); //converts userInput to array and removes whitespace
        var arrayOfResults = new Array();

        //iterates for how many user inputs are recorded into arrayOfUserInput
        for(i = 0; i < arrayOfUserInput.length; i++){
       //awaits for each result of retrieve data before inputing into arrayofresults
         arrayOfResults[i] = await retrieveData(arrayOfUserInput[i]);

        }
        //*****THIS IS THE PART NOT WORKING CORRECTLY****
       console.log(arrayOfResults[0][0]);
     }

     async function retrieveData (clientRecord){
        //pulling data from API
        var request = require("request");
        var resultsArr = new Array();
        var options = { method: 'POST',
        url: 'blah',
        body: ''

        request(options, function (error, response, body) {

        var resData = JSON.parse(body);   //stores json response into object

        // Do Work here
        return  resultsArr;

     }

When I console.log arrayOfResults[0] I recieve all of the data correctly.

When I console.log arrayOfResults [0][0] like above I get undefined unless I put a timeout in to actually wait for the results.

like image 211
Austin Kingrey Avatar asked Nov 17 '22 17:11

Austin Kingrey


1 Answers

    return new Promise(function(resolve, reject) {
        request(options, function (error, response, body) {

        var resData = JSON.parse(body);   //stores json response into object

           if(resData.data.policy_number !== undefined){
             //...........
           } else{
               resultsArr[0] =resData.messages[0];
           }
           resolve(resultsArr);
        });
    });

i codified what Randy suggested for you to get a better idea,

like image 151
DevZer0 Avatar answered Mar 14 '23 21:03

DevZer0