Async/await 函数 return 未定义

Async/await function return undefined

是的,我之前搜索过,是的,这是关于 await/async 函数的另一个问题...

如果我的问题重复但我没有找到解决方案,我提前道歉...

// get result of a poll
async function foo(param) {
    const REACT_OPTS = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', ' '];
    const opts = {
        'key': 'val',
        'other_key': 'other_val'
    };
    const baz = await get_array_baz(param);
    let results = {
        total: 0,
        tab: []
    };

    let r = 0;
    baz.each(function(obj) {
        results.total += obj.num;
        results.tab.push({
            count: obj.num,
            emoji: REACT_OPTS[r]
        });
        r++;
    });

    console.log('results', results);
    return {opts, results};
}

// close a poll
async function bar() {
    // Get poll opts/results and publish channel
    const { opts, res } = await foo(param);
    console.log('bar', opts, res);
}

console.log

> results {
    total: 3,
        tab: [
        { num: 1, emoji: '1️⃣' },
        { num: 0, emoji: '2️⃣' },
        { num: 0, emoji: '3️⃣' },
        { num: 1, emoji: '4️⃣' },
        { num: 0, emoji: '5️⃣' },
        { num: 0, emoji: '6️⃣' },
        { num: 1, emoji: '7️⃣' }
    ]
}
> bar {
    key: 'val',
    other_key: 'other_val'
} undefined

怎么可能?一行可以记录结果,下一行是未定义的......而且更奇怪:为什么 opts 可以通过而不是 results ?

您正在从 foo 函数导出 {opts, results}。在 bar 函数你必须解构同名 { opts, results } 而不是 { opts, res } .

尝试使用下面的栏函数再次 运行 您的代码:

async function bar() {
    // Get poll opts/results and publish channel
    const { opts, results } = await foo(param);
    console.log('bar', opts, results);
}

不过,如果您想使用 res,请为 const { opts, results:res } = await foo(param);

这样的结果提供别名