我有一个使用 hnews.getById(id)返回JSON对象的函数。然后,我将承诺中返回的每个故事推送到数组中。我在弄清楚如何获得完整阵列方面遇到了麻烦。我需要使用另一个承诺吗?
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编辑:我需要返回 storiesArr from updateTopStories();
I need to return storiesArr from updateTopStories();
第二编辑:我是个白痴。 getById 返回一个Promise。我想是时候该睡觉了。 mod可以删除吗?
2nd I'm an idiot. getById is returning a Promise. I think it's time I go to bed. Would a mod please delete this?
我可以从这里拿走它。谢谢大家的光临。
I can take it from here. Thanks all for looking.
推荐答案您正在此处调用多个异步进程。一种常见的处理方法是将id数组映射到Promises数组,所有这些Promises在返回之前都必须解析。
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); });更多推荐
从Promise返回完整的数组
发布评论