I keep running into this problem and need some help understanding how to resolve it.I have a collection of data that is a key to looking up information from an API. I need to go over this collection and look up the data results for each key/item.When I try to do this I always end up with the result of the collection being ran through all together instead of waiting for each individual item to resolve. This gets compounded when I need to do multiple steps on the results depending on what if anything is returned.Here is an extrapolation of what I have right now to solve one such problemdata // is an array of items that need to be lookup up.async function lookup(key) { try { let response = await axios.get(url+key) if (response.data.length > 0) { ...process response... } return processed response } catch (e) { if e.response && e.response.status === 404 { return {error: "404", msg: key+" Item not found"} } else { return {error: e} } async function processList(list) { let resultList = [] for(let i=0; i< list.length; i++) { let results = await lookup(list[i].key) resultList.push(results) } return resultList } // Main Program Here let data = ...data to process... console.log("processing") let results = processList(data) console.log("processed") console.log(results) When i run this the resulting output is always processing then processed then an empty array ... I've lookup up ways to prevent this and so far have ended up with using async/await and putting everything into functions and to use a for loop instead of the .forEach() as that does not wait inside of itself.If I try to mock this more simply without using an actual API I can get it to work, but when using axios it doesn't work the same way.Is there something that I am missing without axios that might be causing these loops to rush through and not wait?
Submitted April 16, 2019 at 12:05AM by coraxwolf
No comments:
Post a Comment