简体   繁体   中英

How to get value from async function?

I am trying to get values from my local database, but all I can get is 'Promise{<Pending>}'. Here is my code that I found on the internet. The code below should return a result object that contains table rows, but I am only getting promise.

const getFromDB = async() =>{
    return  await pool.query('SELECT * FROM services');
};

An async function always returns a promise. The resolved value of that promise is whatever value the code in your function returns. So, to get the value out of that promise, you use either await or .then() ;

getFromDB().then(val => {
    // got value here
    console.log(val);
}).catch(e => {
    // error
    console.log(e);
});

There is no free lunch in Javascript. An value obtained asynchronously can only be returned from a function asynchronous (via callback or promise or other similar async mechanism).

Or, if the caller itself was an async function, then you could use await :

 async function someOtherFunc() {
     try {
         let val = await getFromDb();
         console.log(val);
     } catch(e) {
        // error
        console.log(e);
     }
 }

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