JavaScript:从递归函数返回数组

时间:2018-11-22 13:49:00

标签: javascript node.js ecmascript-6

我制作了一个可以从api构建一些数据的类:

const http = require("http");

class VideoService {

    constructor() {
        this.items = [];
    }

    fetchVideos(token = "") {

        const url = `https://www.example.com`;

        http.getJSON(url).then((results) => {
            results.items.forEach((item, index) => {
                const vid = item.snippet.resourceId.videoId;

                this.items.push({
                    title: item.title,
                    date: item.publishedAt
                });

                console.log(this.items.length); // here length inreases, works here
            });

            if (typeof results.nextPageToken !== "undefined") {
                return this.fetchVideos(results.nextPageToken);
            }

        });
    }

    getVideos() {
        this.fetchVideos();

        console.log(this.items.length); // this returns 0 instead of all items fetched

        return this.items;
    }

}

module.exports = VideoService;

在另一个文件中,我这样使用它:

const videoService = require("../shared/videoService");

const videos = (new videoService()).getVideos();
console.log(videos);

最后一次console.log调用始终返回空数组,而不是返回上述类的items属性中收集的所有数据。

有人可以告诉我我在这里想念的吗?

1 个答案:

答案 0 :(得分:1)

之所以会这样,是因为在函数fetchVideos()中,您正在进行将被异步处理的http调用。您可以尝试通过这种方式进行处理。

fetchVideos(token = "") {

    const url = `https://www.example.com`;

    return http.getJSON(url).then((results) => {
        results.items.forEach((item, index) => {
            const vid = item.snippet.resourceId.videoId;

            this.items.push({
                title: item.title,
                date: item.publishedAt
            });

            console.log(this.items.length); // here length inreases, works here
        });

        if (typeof results.nextPageToken !== "undefined") {
            return this.fetchVideos(results.nextPageToken);
        }
        else return new Promise((resolve, reject)=>{
          resolve();
        });

    });
}

getVideos() {
    return this.fetchVideos().then(function(){
       console.log(this.items.length); // this returns 0 instead of all items fetched
    return this.items;
    });
}

我建议阅读有关javascript中的Promise和异步性的信息。检查此链接: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise