When I run this code
import fetch from 'node-fetch';
const url = "https://jsonplaceholder.typicode.com/todos/1"
const get = async () => {
try {
let response = await fetch(url);
let res = await response.json()
console.log(res);
} catch (err) {
console.error(err);
};
}
( async function(){
await get()
})();
console.log('I am outside')
I get the following output
$ node index.js I am outside
{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }
Why I am not getting output in reverse order? even though I have await for async functions
CodePudding user response:
This is awaited:
await get()
But this is not:
(async function(){
await get()
})();
If you're using a version of Node which supports top-level await
, you can await it:
await (async function(){
await get()
})();
Or follow up the Promise with a callback:
(async function(){
await get()
})().then(() => {
console.log('I am outside');
});
Alternatively, you can move your logic into the IIFE:
(async function(){
await get();
console.log('I am outside');
})();
CodePudding user response:
This part is asynchronous
( async function(){
await get()
})();
I can think of two ways to get the text to display first;
- Move it before the async-function call
- move it into the function call;
CodePudding user response:
In my experience, as David said, you should put code that you want to run after asynchronous code in the defined earlier function's scope. Everything synchronous out of scope will run first
CodePudding user response:
Because this function
( async function(){
await get()
})();
run in asynchronous, so the console.log will print first
If you want run the get()
first, you should do something like
( async function() {
await get();
console.log('I am outside')
})
or another one
( async function() {
await get();
}).then( () => {
console.log('I am outside');
})