Async/await and the returned value

If you declare an asynchronous function in JavaScript, it returns a promise by default.

Example:

javascript
let test = async () => {
    
    await setTimeout(() => (new Promise()).resolve('true'), 5000);
    
    return true;
}

let res = test();

// If you try to print the result 
// While the function is executing
// You'll get an unsolved promise
// Promise {<pending>}
console.log(res); 

// ... Wait 5 seconds ...

// At this point
// The promise will be resolved
// You'll get true value
// Promise {<fulfilled>: true}
console.log(res);

It's not mandatory to return a result on an asynchronous function. If you don't return anything, the promise will be fulfilled with an undefined value.

Example:

javascript
let test = async () => {
    
    await setTimeout(() => (new Promise()).resolve('true'), 5000);
    
}

let res = test();

// If you try to print the result 
// While the function is executing
// You'll get an unsolved promise
// Promise {<pending>}
console.log(res); 

// ... Wait 5 seconds ...

// At this point
// The promise will be resolved
// You'll get true value
// Promise {<fulfilled>: undefined}
console.log(res);

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.