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.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With