【发布时间】:2021-01-30 02:53:50
【问题描述】:
我有 NestJS 应用程序,它与 YoutubeAPI 交互并从中加载视频。
一种特殊的方法很重要,它是下面的loadVideos。它自己的方法内部有多个异步,一旦一切完成,我需要使用 videoIdMap 属性
private loadVideos(
playListId: string,
channel: Channel,
nextPageToken: string,
stopLoadingOnVideoId: string,
) {
const baseUrl = YoutubeService.VIDEO_URL_SNIPPET_BY_ID + playListId;
const response = this.httpService
.get(nextPageToken ? baseUrl + '&pageToken=' + nextPageToken : baseUrl)
.pipe(map((response) => response.data));
response.subscribe((data) => {
data.items.forEach((item) => {
if (stopLoadingOnVideoId && item.snippet.resourceId.videoId === stopLoadingOnVideoId) {
return;
}
this.prepareVideoEntity(item.snippet, channel).then((partialVideo) =>
this.videoService.create(partialVideo).then((video) => {
this.videoIdMap[video.youtubeId] = video.id;
}),
);
});
if (data.nextPageToken) {
this.loadVideos(
playListId,
channel,
data.nextPageToken,
stopLoadingOnVideoId,
);
}
});
}
对我来说理想的解决方案是以某种方式使 loadVideos 异步,以便我以后可以这样做:
public methodWhichCallLoadVideos(): void {
await loadVideos(playListId, channel, null, stopLoadingOnVideoId)
// My code which have to be executed right after videos are loaded
}
我尝试的每个解决方案都以 this.videoIdMap 为空对象或存在编译问题,因此任何想法都非常受欢迎。
【问题讨论】:
-
为了“等待”加载视频,您需要将其设为“异步”。为此,它必须返回一个 promise,而 Nest 的 HttpService 返回一个 observable。检查这个问题:stackoverflow.com/questions/51910908/…
标签: express promise observable es6-promise nestjs