Skip to content

Instantly share code, notes, and snippets.

@nikkaroraa
Created May 3, 2018 14:30
Show Gist options
  • Save nikkaroraa/de759bdfc84060c12c2be0b4454f3200 to your computer and use it in GitHub Desktop.
Save nikkaroraa/de759bdfc84060c12c2be0b4454f3200 to your computer and use it in GitHub Desktop.
Callbacks, Promises and Async/Await
// The Problem
function fn(val) {
setTimeout(function() {
console.log(val)
}, val)
}
function executeAll() {
fn(20)
fn(20)
fn(400)
fn(20)
}
executeAll()
// The Solution (through callback)
function fn(val, callback) {
setTimeout(function() {
console.log(val)
callback()
}, val)
}
function executeAll() {
fn(20, function() {
fn(20, function() {
fn(400, function() {
fn(20, function() {
})
})
})
})
}
executeAll()
// The Solution (through Promise)
function fn(val) {
return new Promise(function (resolve, reject) {
setTimeout(function() {
console.log(val)
resolve()
}, val)
})
}
function executeAll() {
fn(20).then(function() {
return fn(20)
}).then(function() {
return fn(400)
}).then(function() {
return fn(20)
})
}
executeAll()
// The Solution (through Async/Await)
function fn(val) {
return new Promise(function (resolve, reject) {
setTimeout(function() {
console.log(val)
resolve()
}, val)
})
}
async function executeAll() {
await fn(20)
await fn(20)
await fn(400)
await fn(20)
}
executeAll()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment