Skip to content

Instantly share code, notes, and snippets.

@GonchuB
Created November 13, 2018 14:53
Show Gist options
  • Save GonchuB/ba50aaaabe87d9946002ada1cf82cdb4 to your computer and use it in GitHub Desktop.
Save GonchuB/ba50aaaabe87d9946002ada1cf82cdb4 to your computer and use it in GitHub Desktop.
Async correction
// Original function definition with comments
async function asyncFunc() {
let data; // data variable gets declared, but it is `undefined`
// The promise returned by `axios.get` is not returned
axios.get("/some_url_endpoint")
.then((result) => {
// When this GET call gets resolved, we assign data variable to the result
data = result
});
// We return data (internally, it will be a promise resolved with the value of data).
// But data is `undefined` when this function gets called (because of how JS works, basically)
// You can read a bit more about it in https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
// I really recommend that article
return data;
}
const data = await asyncFunc();
// data => undefined
// So your function could be something like this in order to work
async function asyncFuncV2() {
let data;
// fetch data from a url endpoint
return axios.get("/some_url_endpoint")
.then((result) => {
data = result
return data;
});
}
const dataV2 = await asyncFuncV2();
// data => result from axios.get
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment