Monday 24 February 2020

async await unexpected results issue

I have a recursive function that pulls a set of pages from an API. The end results are being lose somewhere along the way.The pages are paginated and i am using the parse-link-header npm library to process the series of headers. Once all the pages have been retrieved it should return the array list back. Instead I am ended up with the value being undefined.I can give a simplified version of my code, but I don't know of any free apis that have this paging style setup. The api that I am using is private so I can't give the exact code that I am working with as an example.the recursive function is:const getAll = async (params, results = []) => { try { const resp = await axios.get(params.url); for (const data of resp.data) { if (data.cond === params.cond) { results.push(data); } else { params.missed += 1; } const links = linkParser(resp.header.links); // parse-link-header library if (links.next) { params.url = links.next.url; await getAll(params, results); } else { return(results); } } catch(err) { console.error(err); return([]); } } This function is called from another function like so:const processRecs = async (cond, days = 90, id) => { const startDate = moment().subtract(days, 'd'); const params = { url: `users/${id}/records?start_date=${startDate}', cond: cond, }; const records = await getAll(params); // shouldn't need to pass an empty [] as that is default console.log(records); }When that function is used records come out as undefined always. I've added in console.log statements that show that I am getting results from the API and they are happening in order. if I add a console.log(results) right before the return(results) in the first function I can see all of the results, but they aren't being assigned into records in the second function.I am completely lost as to what is going on here. usually with async await my issue is that something isn't waiting, but here I can watch the different api calls go out one after another and see the responses come in so that isn't the issue here.any help would be greatly appreciated.

Submitted February 24, 2020 at 08:23PM by coraxwolf

No comments:

Post a Comment