Promises in a sync style in JavaScript

To solve the problem of promise hell, a special promise syntax was invented that allows you to write async code much easier - in a synchronous style.

Let's start studying it. First, let's take the code from the previous lesson:

function func() { getSmth(2).then(res => { console.log(res); // shows 4 }); } func();

If our getSmth function was synchronous, then we could rewrite the code of the func function as follows:

function func() { let res = getSmth(2); console.log(res); // shows 4 }

The getSmth function, however, is asynchronous, so the above code won't work. But using the sync style of promises, we can get something similar. Let's do it.

First we need to declare our func function as asynchronous with the special async command:

async function func() { }

After that, we can use the special await command inside the func function. This command, written before a promise, will cause JavaScript to wait until the promise is fulfilled. After that, the command will return the result of the promise, and code execution will continue.

In our case, we must write await before calling getSmth. Since the result of calling this function will be a promise, further code execution will continue only after this promise has been fulfilled. Well, the result of the promise can be written to a variable. Let's do the described:

async function func() { let res = await getSmth(2); console.log(res); // shows 4 } func();

Let's call the getSmth a few times:

async function func() { let res1 = await getSmth(2); let res2 = await getSmth(3); console.log(res1 + res2); // shows 13 } func();

And now we will call the getSmth in a loop:

async function func() { let arr = [1, 2, 3, 4, 5]; let sum = 0; for (let elem of arr) { sum += await getSmth(elem); } console.log(sum); } func();

Rewrite the following code using sync syntax:

function func() { getSmth(2).then(res1 => { getSmth(3).then(res2 => { getSmth(4).then(res3 => { console.log(res1 + res2 + res3); }); }); }); } func();
enru