首页 > 解决方案 > 有没有更好的方法在没有承诺的情况下返回异步数据?

问题描述

我有这个函数应该使用 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) })
    })
}

有没有更好的方法来实现这一点?

标签: javascriptnode.jsasynchronouspromiseyoutube-api

解决方案


如果你可以链接.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);

推荐阅读