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?
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'); }
);
}
Since aaa returns a Promise, you can always interact directly with that Promise instead of using await. For example:
function index() {
console.log('1');
aaa().then(() => console.log('3'));
}
That way the code in the .then() callback won't execute until after the Promise returned by aaa() resolves.
For the most part, without peeking under the hood to the inner workings of JavaScript, async and await tends to just be a cleaner and simpler way of expressing this same thing. For this simple example, there really shouldn't be a meaningful difference between this:
function index() {
console.log('1');
return aaa().then(() => console.log('3'));
}
And this:
async function index() {
console.log('1');
await aaa();
console.log('3');
}
The main difference between these and the function at the top of this answer is that the one at the top doesn't advertise that it internally has asynchronous operations. So it can't be awaited. If that's not an issue for your needs, no big deal. But even then, going with async and await still does the same thing and consuming code can simply choose not to await this function.