【发布时间】:2019-04-25 05:24:17
【问题描述】:
我已经创建了一个从 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 属性中收集的所有数据。
谁能告诉我这里缺少什么?
【问题讨论】:
-
是的,所以你的函数
fetchVideos()有一个 http 调用,它将被异步处理。我建议使用 Promise 或 Observable 之类的东西。您可以在此处阅读有关 Promises 的更多信息。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
详细说明:对
.getJSON()的调用立即返回,在收到对底层 HTTP 请求的响应之前。 -
@Pointy:谢谢,但我对 Promise 的东西相当陌生,我不明白如何修改此代码以使用 Promise。我很乐意看到答案中的修复,所以我可以接受它。谢谢
-
您的主要问题是在递归结束时您没有返回(已解决的)承诺。
-
也许the following answer 可以帮助您根据先前请求的结果提出请求。
标签: javascript node.js ecmascript-6