I'm quite a newbie in JavaScript and in Promises. I'm trying to build an array of objects that I get from an API.
To do so, I've build two functions in a file MyFile.js
.
The first one returns a promise when an axios promise is resolved. It's
function get_items (url) {
return new Promise((resolve, reject) => {
let options = {
baseURL: url,
method: 'get'
}
axios(options)
.then(response => {
resolve(response.data)
})
.catch(error => {
reject(error.stack)
})
})
}
The second one looks like this:
let output = []
let next_url = 'https://some_url.com/api/data'
async function get_data () {
try {
let promise = new Promise((resolve, reject) => {
if (next_url) {
get_items(next_url)
.then(response => {
output.push(...response.results)
if (response.next) {
next_url = response.next
console.log('NEXT_URL HERE', next_url)
get_data()
} else {
console.log('else')
next_url = false
get_data()
}
})
.catch(error => {
reject(error.stack)
})
} else {
console.log('before resolve')
resolve(output)
}
})
return await promise
} catch(e) {
console.log(e)
}
}
It's where I'm grinding my teeth. What I think I understand of this function, is that:
- it's returning the value of a promise (that's what I understand
return await promise
is doing) - it's a recursive function. So, if there is a next_url, the function continues on. But if there is not, it gets called one last time to go into the
else
part where it resolves the arrayoutput
which contains the results (values not state) of all the promises. At least, when I execute it, and check for my sanity checks with theconsole.log
I wrote, it works.
So, output
is filled with data and that's great.
But, when I call this function from another file MyOtherFile.js
, like this:
final_output = []
MyFile.get_data()
.then(result => {
console.log('getting data')
final_output.push(...result)
})
it never gets into the then
part. And when I console.log MyFile.get_data()
, it's a pending promise.
So, what I would like to do, is be able to make get_data()
wait for all the promises result (without using Promise.all(), to have calls in serie, not in parallel, that would be great for performances, I guess?) and then be able to retrieve that response in the then
part when calling this function from anywhere else.
Keep in mind that I'm really a newbie in promises and JavaScript in general (I'm more of a Python guy).
Let me know if my question isn't clear enough. I've been scratching my head for two days now and it feels like I'm running in circle.
Thanks for being an awesome community!