CodeNewbie Community

loading...

Asynchronous JavaScript Tips

ender minyard
💻
・1 min read

To define a synchronous function, you have a few options:

let myFunc = () => {...}

function myFunction(){
...
}
Enter fullscreen mode Exit fullscreen mode

Defining function expressions and arrow functions asynchronously looks somewhat different:


let myFunc = async () => {...}

async function myFunction {
...
}
Enter fullscreen mode Exit fullscreen mode

Understanding await has helped me a lot.

[rv] = await expression;
Enter fullscreen mode Exit fullscreen mode

expression: The promise you're waiting for.

rv: The fulfilled value of the promise.

(You can only use await inside asynchronous functions.)

If you have a promise, this code will fail:

let p1 = Promise.resolve(3);
console.log(p1);
Enter fullscreen mode Exit fullscreen mode

But this code will not.


let p1 = Promise.resolve(3);

let myFunc = async () => {
let resolved = await p1;
console.log(resolved); //3
}

myFunc(); // You also could have used an IIFE
Enter fullscreen mode Exit fullscreen mode

It's also useful (and fun!) to understand promises.

Discussion (0)