简体   繁体   中英

return async function undefined in es6

Here, plcs variable within try catch function need to be used outside. I am trying calling async function directly and storing in sync function, both doesn't work, first method shows undefined and next one returns null promise

const fetch = () =>{
    const result=async()=>{
        try {
            const dbResult = await ftchplc();
            plcs= dbResult.rows._array;
            return plcs
        } catch (err) {
            throw err;
        }
    }
    return result()
}    
const sample = fetch()
console.log(sample)


const result=async()=>{
    try {
        const dbResult = await ftchplc();
        plcs= dbResult.rows._array;
        return plcs
    } catch (err) {
        throw err;
    }
}
result()
const sample = result()

ALL async functions return a promise. So you will have to use await or .then() when you call an async function in order to get the resolved value.

async functions are useful INSIDE the function so you can use await internal to the function, but to the outside caller, it's still just a promise being returned. async functions to not turn an asynchronous result into a synchronous result. The caller of an async function still has to deal with an asynchronous response (in a promise).

For example:

async function fn() {
    const dbResult = await ftchplc();
    return dbResult.rows._array;
 };

fn().then(sample => {
    console.log(sample);
}).catch(err => {
    console.log(err);
});

This assumes that ftchplc() returns a promise that resolves to your expected dbResult .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM