'Is it possible to run an asynchronous function without making the main function as async?

Is it possible to run an asynchronous function without making the main function as async?

function index() {
    console.log('1');
    aaa();
    console.log('3');
}

async function aaa() {
    return await bbb().then((value) => {
        console.log(value);
    });
}

async function bbb() {
    return await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('2');
        }, 1000);
    });
}

index();

It is possible to display:

1

2

3

Without making the index function as async?



Solution 1:[1]

You need to do something to cause console.log('3') to run after the promise returned by aaa() has been resolved.

Making index async and using await is the approach that most people find easiest to write and maintain.

async function index() {
    console.log('1');
    await aaa();
    console.log('3');
}

You could use then() instead.

function index() {
    console.log('1');
    aaa().then(
        () => { console.log('3'); }
    );
    
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quentin