Javascript Asynchronous, Callback, Promise and Async/Await questions

async function getUser() {
const response = await fetch('https://api.github.com/users/octocat')
const data = await response.json()
console.log(data)
}
// Execute async function
getUser()
// Fetch a user from the GitHub API
fetch('https://api.github.com/users/octocat')
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data)
})
.catch((error) => {
console.error(error)
})
function printString(string, callback) {  
setTimeout(() => {
console.log(string)
callback()
},1 * 1000)
}
function printAll() {
printString("A", () => {
printString("B", () => {
printString("C", () => {
})
})
})}
printAll()
function printString(string) { 
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(string)
resolve()
}, 1 * 1000)})
}
function printAll() {
printString("A").then(() => {
return printString("B")
}).then(() => {
return printString("C")
})
}
printAll()
function printString(string) { 
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(string)
resolve()
}, 1 * 1000)})
}
async function printAll() {
await printString("A")
await printString("B")
await printString("C")
}
printAll()
var p = new Promise((resolve, reject) => {
reject(Error('The Fails!'))
})
p.catch(error => console.log(error.message))
p.catch(error => console.log(error.message))
var p = new Promise((resolve, reject) => {
return Promise.reject(Error('The Fails!'))
})
p.catch(error => console.log(error.message))
p.catch(error => console.log(error.message))
var p = new Promise((resolve, reject) => {
reject(Error('The Fails!'))
})
.catch(error => console.log(error))
.then(error => console.log(error))
var p = new Promise((resolve, reject) => {
reject(Error('The Fails!'))
})
.catch(error => console.log(error.message))
.catch(error => console.log(error.message))
new Promise((resolve, reject) => {
resolve('Success!')
})
.then(() => {
throw Error('Oh noes!')
})
.catch(error => {
return "actually, that worked"
})
.catch(error => console.log(error.message))
Promise.resolve('Success!')
.then(data => {
return data.toUpperCase()
})
.then(data => {
console.log(data)
})
Promise.resolve('Success!')
.then(data => {
return data.toUpperCase()
})
.then(data => {
console.log(data)
return data
})
.then(console.log)
Promise.resolve('Success!')
.then(data => {
data.toUpperCase()
})
.then(data => {
console.log(data)
})
Promise.resolve('Success!')
.then(() => {
throw Error('Oh noes!')
})
.catch(error => {
return 'actually, that worked'
})
.then(data => {
throw Error('The fails!')
})
.catch(error => console.log(error.message))

--

--

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