lynxx
lynxx

Reputation: 596

difference between different scenarios of async await

What is the difference between the following scenarios:

scenario 1 - async-await in axios request - DOES NOT WORK

export const getAll = async () => {
    const retrievedData = await axios.get('http://localhost:3001/anecdotes'); // should return - Array
    return retrievedData.data;
};


const test = () => {
        let anecdotes = getAll();
        // do something 
    };

Scenario 2 - async-await in helper method DOES NOT WORK

export const getAll = () => {
    const retrievedData = axios.get('http://localhost:3001/anecdotes'); // should return - Array
    return retrievedData.data;
};


const test = async () => {
        let anecdotes = await getAll();
        // do something 
    };

Scenario 3 - async-await in both WORKS

export const getAll = async() => {
    const retrievedData = await axios.get('http://localhost:3001/anecdotes'); // should return - Array
    return retrievedData.data;
};


const test = async () => {
        let anecdotes = await getAll();
        // do something 
    };

What is the difference between the above scenarios? Why does only 3rd case work??

Upvotes: 2

Views: 585

Answers (1)

jfriend00
jfriend00

Reputation: 707376

Why does only 3rd case work??

All async functions return a promise - always. When you return a value in an async function, that value becomes the resolved value of the promise that the async function returns.

In addition, axios() returns a promise so you also need to use .then() or await on its return value to get the result from the axios() call too.

Scenario 1

In scenario 1, Your getAll() function is async and returns a promise. Then your test() function doesn't use await or .then() on that promise:

const test = () => {
        let anecdotes = getAll();
        // do something 
};

Therefore anecdotes is just a promise and you haven't actually gotten the value out of the promise. You need to use await or .then() on that promise to get the value.


Scenario 2

Scenario 2 has a slightly different problem. In getAll()you do this:

export const getAll = () => {
    const retrievedData = axios.get('http://localhost:3001/anecdotes');
    return retrievedData.data;
}

axios.get() returns a promise. So, retrievedData is a promise. It's not the result you want. When you return retrievedData.data, you're just returning a non-existing property of the promise so it will always return undefined.


Scenario 3

In scenario 3, you do successfully use await on the result of the async function and on the result of the axios() call and thus it works.

export const getAll = async() => {
    const retrievedData = await axios.get('http://localhost:3001/anecdotes'); // should return - Array
    return retrievedData.data;
};


const test = async () => {
    let anecdotes = await getAll();
    // do something 
};

Upvotes: 3

Related Questions