从Promise返回完整的数组

编程入门 行业动态 更新时间:2024-10-10 02:18:57
本文介绍了从Promise返回完整的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个使用 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返回完整的数组

本文发布于:2023-11-28 04:06:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640889.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   完整   Promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!