【问题标题】:Is there a better way of returning async data without promises?有没有更好的方法在没有承诺的情况下返回异步数据?
【发布时间】: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。或者如果是,它至少可以在正文中使用awaitconst res = await getChannelStats(channelId); return res.viewCount;
  • 我想你可以这样做const getChannelViews = async (channelId) => (await getChannelStats(channelId)).viewCount
  • 尝试 await 关键字,因为您已经在使用 async 关键字

标签: javascript node.js asynchronous promise youtube-api


【解决方案1】:

如果您可以将 .then() 链接到某个东西,通常意味着它已经是一个 Promise。因此,没有必要将那个 Promise 包装在另一个 Promise 中,并在内部 Promise 解析时解析外部 Promise,这是矫枉过正和不优雅。

此外,使用.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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-08
    • 2019-11-26
    • 2015-12-21
    • 1970-01-01
    • 2017-12-05
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多