-1

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()
Bijaya
  • 31
  • 4
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ASDFGerte Dec 15 '19 at 21:50
  • It's unclear what you are trying to achieve here. But given that `ftchplc` is asynchronous and returns a promise, getting the `plcs` is always an asynchronous action and you will need to make your `console.log` wait for the result no matter what. Unnecessarily nesting the `result` function in a `fetch` function doesn't help anything. – Bergi Dec 15 '19 at 21:52
  • 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. – jfriend00 Dec 15 '19 at 22:08

1 Answers1

0

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979