'How to make synchronous api calls in node js?
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.jsI 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?
Solution 1:[1]
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');
})();
Solution 2:[2]
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;
Solution 3:[3]
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
Solution 4:[4]
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');
})
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 | David |
| Solution 2 | Isfaaq |
| Solution 3 | Adis Jumadylov |
| Solution 4 | tuphamdev96 |
