Chain asynchronous functions?

let val = 0;

async function first() {
    console.log('1a', val);
    second();
    console.log('1b', val);
}

async function second() {
    console.log('2a', val);
    third();
    console.log('2b', val);
}

async function third() {
    console.log('3a', val);
    val = await new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(3);
        }, 1000);
    });
    console.log('3b', val);
}

console.log('0a', val);
first();
console.log('0b', val);

I expect:

0a 0
1a 0
2a 0
3a 0
3b 3
2b 3
1b 3
0b 3

But I get:

0a 0
1a 0
2a 0
3a 0
2b 0
1b 0
0b 0
3b 3

I assume there is a fundamental thing in async that I don't know about?

+4
source share
2 answers

You will need to use

async function first() {
    console.log('1a', val);
    await second();
//  ^^^^^
    console.log('1b', val);
}

async function second() {
    console.log('2a', val);
    await third();
//  ^^^^^
    console.log('2b', val);
}

to bind the logs bafter asynchronously executing the called functions.

And it's the same for

console.log('0a', val);
first();
console.log('0b', val);

, await , aync function. async , , - , , await. 0b wait,

console.log('0a', val);
first().then(function() {
    console.log('0b', val);
}, function(err) {
    console.error(err);
});

(async function() {
    try {
        console.log('0a', val);
        first();
        console.log('0b', val);
    } catch(err) {
        console.log(err);
    }
}());
+2

await async:

async function first() {
    console.log('1a', val);
    await second();
    console.log('1b', val);
}

async function second() {
    console.log('2a', val);
    await third();
    console.log('2b', val);
}
+4

Source: https://habr.com/ru/post/1658009/


All Articles