javascript - 有没有更好的方法在没有承诺的情况下返回异步数据?
问题描述
我有这个函数应该使用 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) })
})
}
有没有更好的方法来实现这一点?
解决方案
如果你可以链接.then()
到某个东西,一般来说这意味着它已经是一个 Promise。因此,没有必要将那个 Promise 包装在另一个 Promise 中,并在内部 Promise 解析时解析外部 Promise,这是矫枉过正和不雅的。
此外,不是 using .then()
,而是更容易使用await
:
const getChannelStats = async (chId) => {
const res = await google.youtube("v3").channels.list({
key: token,
part: "statistics",
id: chId,
})
return res.data?.items?.[0]?.statistics // This is a Promise. Async functions always return Promises. So you can do await getChannelStats()
}
const getChannelViews = async (channelId) => (await getChannelStats(channelId)).viewCount;
const viewsCount = await getChannelViews(someChannelId);
console.log("viewsCount = ", viewsCount);
推荐阅读
- flutter - 如何在使用颤振从侧面菜单抽屉导航时取消隐藏应用栏和底部导航栏?
- javascript - 用户关闭弹窗后如何申请优惠码?
- python - Firebase admin .listen() AttributeError 的问题
- jquery - 如何使用下一个和上一个图像制作轮播?
- unity3d - android deploymant统一构建失败
- jquery - 如何获取选择器的零件名称?
- android - 在 Android 中使用 Tenserflow 计算与相机的物距
- asp.net-mvc - Kendo DataSourceRequest 对象中的反射 XSS
- flutter - 弹出警告框
- rest - Web API Core 3.1 中的参数绑定(字符串到整数)