I have a function that returns JSON objects using hnews.getById(id). I then push each story returned in the promise to an array. I'm having trouble figuring out how I'd then get the complete array. Do I need to use another promise?
function updateTopStories() {
var storiesArr = [];
hnews.getIdsInCategory('topstories', 60)
.then(function(ids) {
ids.forEach(function(id) {
hnews.getById(id).then(function(story) {
console.log(story);
storiesArr.push(story);
});
});
});
return storiesArr;
}
var stories = updateTopStories();
console.log(stories); // Empty array
EDIT: I need to return storiesArr from updateTopStories();
You are invoking multiple async processes here. A common way of handling this is to map your array of ids to an array of Promises which all have to resolve before returning. See if this works for you.
function updateTopStories() {
return hnews.getIdsInCategory('topstories', 60).then(function(ids) {
var promises = ids.map(function(id) {
return hnews.getById(id);
});
return Promise.all(promises);
});
}
updateTopStories().then(function(stories) {
console.log(stories);
});
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