To understand promises and callbacks you should checkout this talk
Event Loop. Javascript event loop at first runs all synchronous code, that means
console.log
runs before any of your promise code, that is why x is undefined
, callback inside .then(...)
will run after all synchronous code and after all callbacks (there is difference between callbacks and promises)
You can think of promise like you have postponed something to run later.
async => await
is just a syntactic sugar for promises, it makes our javascript look like synchronous code but it's asynchronous. Everything that i said for promises is still valid inside async => await
(they are just promises)
async function asynFunction() {
const x = await get_API();
console.log(x);
}
this function is the same as:
function f() {
get_API().then(data => {
let x = data;
console.log(x));
})
}
not as:
function f() {
let x;
get_API().then(data => x = data)
console.log(x)
}
Resources for callbacks and promises:
Async JS Crash Course - Callbacks, Promises, Async Await
MDN Prmises
MDN Callbacks
JavaScript is not the same as other languages, you need to wrap your head around the event loop. and do everything "JavaScript Way".
Answer to your question:
function get_API() {
let url = "http://example.com";
return fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data);
return data;
});
}
fetch
function has two promises by default, first to get the response from the server, second you use to format the data. If you would like to use it like this
function f() {
get_API().then(data => {
let x = data;
console.log(x));
})
}
your api function has to be changed
function get_API() {
let url = "http://example.com";
return fetch(url)
.then((response) => response.json());
}
now your function returns a promise and you can use .then
inside another function and get the data.