Reputation: 187
I have some doubts on this code, why the below code is print "end" before completing fetchData request. Javascript is not asynchronous. then why end method run before completing fetchdata
function start(){
console.log("start")
}
function fetchData(){
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
}
function end(){
console.log("end")
}
start()
fetchData()
end()
Upvotes: 0
Views: 72
Reputation: 30675
You'll need to return the promise from fetch and then await the fetchData, in an async. function. Fetch returns a promise and returns immediately, we have to await the promise to ensure the order of calls is preserved.
function start(){
console.log("start")
}
function fetchData(){
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
}
function end(){
console.log("end")
}
(async() => {
start()
await fetchData()
end()
})();
The async/await pattern gives us asynchronous code that's a lot easier to read than having a bunch of callbacks, see await
Upvotes: 0
Reputation: 13
This happens because fetch makes an asynchronous call. To get a clear understanding of how the JS event loop works, have a look at JS event loop
Upvotes: 0
Reputation: 1227
Your fetchData() function is async. Check out the docks on MDN.
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
Upvotes: 1
Reputation: 129
Requests in javascript are asynchronous. You can tell because of the promise it returns (thats why you are able to call then
after fetch)
So fetch request is sent, then end
function gets called and whenever fetch returns it will output its result, thats why you see end
printed before, cause for sure http requests is taking at least some miliseconds
Upvotes: 0
Reputation: 4446
In this case the request is async. Reading the docs on fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API we can see:
The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise ...
Promises are async.
If you need to wait for the data, do something like Terry Lennox's answer.
Upvotes: 0