【发布时间】:2021-08-10 12:13:03
【问题描述】:
我有这个函数应该使用 youtube v3 数据 api 只返回来自 youtube 频道的原始统计数据
var getChannelStats = function (chId) {
return new Promise((resolve, reject) => {
google.youtube("v3").channels.list({
key: token,
part: "statistics",
id: chId,
}).then(res => {
resolve(res.data?.items?.[0]?.statistics)
})
})
};
然后我想要多个函数只从统计中返回特定信息
async function getChannelViews(channelId) {
return new Promise(resolve => {
getChannelStats(channelId).then(res => { resolve(res.viewCount) })
})
}
有没有更好的实现方式?
【问题讨论】:
-
您不必要地使用了 Promise 构造函数 - 当您已经拥有一个 Promise 时不要创建它。
getChannelViews应该只返回getChannelStats(...)和getChannelStats应该只返回google.youtube(...).channels.list(....) -
@Yousaf 还有,
getChannelViews可能不应该是async。或者如果是,它至少可以在正文中使用await:const res = await getChannelStats(channelId); return res.viewCount; -
我想你可以这样做
const getChannelViews = async (channelId) => (await getChannelStats(channelId)).viewCount -
尝试 await 关键字,因为您已经在使用 async 关键字
标签: javascript node.js asynchronous promise youtube-api