有没有更好的方法在没有承诺的情况下返回异步数据?

Is there a better way of returning async data without promises?

我有这个功能,它应该 return 仅来自使用 youtube v3 数据的 youtube 频道的原始统计数据 api

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)
        })
    })
};

然后我想有多个函数来仅return来自统计数据的特定信息

async function getChannelViews(channelId) {
    return new Promise(resolve => {
        getChannelStats(channelId).then(res => { resolve(res.viewCount) })
    })
}

有没有更好的实现方式?

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