Promises 101 and Fetch, Axios and $.ajax

What is the problem?

myfunction(() => {
console.log("this is a callback function")
myfunction(() => {
console.log("this is a callback function")
myfunction(() => {
console.log("this is a callback function")
myfunction(() => {
console.log("this is a callback function")
myfunction(() => {
console.log("this is a callback function")
})
})
})
})
})

Enter Promises

const promise1 = functionThatReturnsPromise()promise1
.then(data => {
console.log("I run when the promise resolves")
console.log("the promise returned: ", data)
})
.catch(err => {
console.log("I run when the promise fails")
console.log("This is the error: ", err)
})
const allPromises = Promise.all([promise1, promise2, promise3])allPromises
.then(data => {
console.log("I run when all promises resolves")
console.log("the promise returned: ", data)
})
.catch(err => {
console.log("I run when if any of the promises fail")
console.log("This is the error: ", err)
})

When Do you use promises?

Fetch

// We run fetch, a promise is returned
const request = fetch("https://jsonplaceholder.typicode.com/posts/1")
//When resolved, we'll run the function to convert the buffer
const response = request.then(res => res.json())
//Then we can use the json data as we wish
response.then(data => {
console.log(data)
})
// We run fetch, a promise is returned
const request = fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(res => res.json()) // We convert the buffer
.then(data => {
//Do stuff with the data
console.log(data)
})
const getData = async () => {
// We run fetch, a promise is returned
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1")
// we convert the buffer
const data = await response.json()
// We can use the data
console.log(data)
}
getData()

$.ajax

const getData = async () => {
// We run $.ajax, a promise is returned
const data = await $.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
})
// We can use the data
console.log(data.data)
}
getData()

Axios

const getData = async () => {
// We run axios, a promise is returned
const data = await axios({
url: "https://jsonplaceholder.typicode.com/posts/1",
})
// We can use the data
console.log(data.data)
}
getData()

In conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alex Merced Coder

Alex Merced Coder

59 Followers

Alex Merced is a Developer Advocate for Dremio and host of the Web Dev 101 and Datanation Podcasts.