9_JavaScript_Callbacks_Promises_Async_and_Await
9_JavaScript_Callbacks_Promises_Async_and_Await
JavaScript
higherOrderFunction(fn)
Nested Callbacks
function pyramidOfDoom() {
setTimeout(() => {
console.log(1)
setTimeout(() => {
console.log(2)
setTimeout(() => {
console.log(3) Output:
}, 500) 1
}, 2000) 2
}, 1000) 3
}
Promise
A promise represents the completion of an asynchronous function
// Initialize a promise
const promise = new Promise((resolve,
reject) => {})
Promise
A promise can have three possible states: pending,
fulfilled, and rejected.
function pyramidOfDoom() {
delay(1000)
.then(() => {
function pyramidOfDoom() { console.log(1);
setTimeout(() => { return delay(2000);
})
console.log(1) .then(() => {
setTimeout(() => { console.log(2);
return delay(500);
console.log(2) })
setTimeout(() => { .then(() => {
console.log(3) console.log(3);
})
}, 500) .catch(error => console.error(error));
}, 2000) }
}, 1000)
// Call the function
} pyramidOfDoom();
function delay(ms) {
return new Promise(resolve => setTimeout(resolve,ms));
}
function pyramidOfDoom() {
delay(1000)
.then(() => {
console.log(1);
return delay(2000);
})
.then(() => {
console.log(2);
return delay(500);
})
.then(() => {
console.log(3);
})
.catch(error => console.error(error));
}
function sumAsync(x, y) {
return new Promise((resolve, reject) => {
sleep(500).then(() => {
resolve(x + y);
});
});
}