Created
January 6, 2024 07:29
-
-
Save ngnguyen1/12b66a5925ae2d922c36f4d6aa4908fd to your computer and use it in GitHub Desktop.
Using Promises, Async/await to fix callback hell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function doStep1(init, callback) { | |
const result = init + 1 | |
callback(result) | |
} | |
function doStep2(init, callback) { | |
const result = init + 2 | |
callback(result) | |
} | |
function doStep3(init, callback) { | |
const result = init + 3 | |
callback(result) | |
} | |
function doStep4(init, callback) { | |
const result = init + 4 | |
callback(result) | |
} | |
function doOperationCallback() { | |
doStep1(0, (result1) => { | |
doStep2(result1, (result2) => { | |
doStep3(result2, (result3) => { | |
doStep4(result3, (total) => { | |
console.log(`Total is: ${total}`) | |
}) | |
}); | |
}); | |
}); | |
} | |
doOperationCallback() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function doStep1(init) { | |
const result = init + 1 | |
return new Promise((resolve, reject) => { | |
resolve(result) | |
}) | |
} | |
function doStep2(init) { | |
const result = init + 2 | |
return new Promise((resolve, reject) => { | |
resolve(result) | |
}) | |
} | |
function doStep3(init) { | |
const result = init + 3 | |
return new Promise((resolve, reject) => { | |
resolve(result) | |
}) | |
} | |
function doStep4(init) { | |
const result = init + 4 | |
return new Promise((resolve, reject) => { | |
resolve(result) | |
}) | |
} | |
function doOperationPromise() { | |
return new Promise((resolve, reject) => { | |
resolve(0) | |
}) | |
.then(doStep1) | |
.then(doStep2) | |
.then(doStep3) | |
.then(doStep4) | |
.then(total => console.log(`Total is: ${total}`)) | |
} | |
async function doOperationAsyncAwait() { | |
const result1 = await doStep1(0) | |
const result2 = await doStep2(result1) | |
const result3 = await doStep3(result2) | |
const total = await doStep4(result3) | |
console.log(`Total is: ${total}`) | |
} | |
doOperationPromise() | |
doOperationAsyncAwait() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment