繁体   English   中英

返回 es6 中未定义的异步函数

[英]return async function undefined in es6

这里, try catch函数中的plcs变量需要在外部使用。 我正在尝试直接调用async函数并存储在sync函数中,两者都不起作用,第一个方法显示未定义,下一个返回空承诺

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()

所有async函数都返回一个承诺。 因此.then()当您调用async函数时,您必须使用await.then()以获得解析的值。

async函数在函数内部很有用,因此您可以在函数内部使用await ,但对于外部调用者来说,它仍然只是一个被返回的承诺。 async函数不会将异步结果转换为同步结果。 async函数的调用者仍然必须处理异步响应(在承诺中)。

例如:

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

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

这假设ftchplc()返回一个可解析为您预期的dbResult的承诺。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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