Chenille33
Chenille33

Reputation: 191

Async/await function return undefined

Yes I search before and yes this is annother question about await/async function...

I'm sorry in advance if my question is a duplicate but I don't found solution...

// 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

How it is possible ? One line can log result, the next line is undefined... And more strange : why opts can pass and not results ?

Upvotes: 0

Views: 235

Answers (1)

user10014185
user10014185

Reputation:

You are exporting {opts, results} from foo function. And in bar function you must destructure with same name like { opts, results } instead of { opts, res } .

try to run your code again by using below bar function :

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

Still if you want to use res then provide alias for results like const { opts, results:res } = await foo(param);

Upvotes: 2

Related Questions