从Promise返回完整的数组 [英] Return complete array from Promise

查看:194
本文介绍了从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返回完整的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆