Last active
September 10, 2020 08:25
-
-
Save rameshbaskar/896ff59b1426b5c5f53bffa3880b8d77 to your computer and use it in GitHub Desktop.
Example JS code on Promises using async/await with promise rejection
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
async function capitalize(text, timeout) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
let firstChar = text.charAt(0); | |
if (text.charAt(0).toUpperCase() === firstChar) { | |
reject('First character is already capitalized'); | |
} else { | |
resolve(text.charAt(0).toUpperCase() + text.slice(1)); | |
} | |
}, timeout); | |
}); | |
} | |
async function createName(firstName, lastName) { | |
let capitalizedFirstName = await capitalize(firstName, 200) | |
.then(name => {return name;}) | |
.catch(e => { | |
console.log(e); | |
return firstName; | |
}); | |
let capitalizedLastName = await capitalize(lastName, 300) | |
.then(name => {return name;}) | |
.catch(e => { | |
console.log(e); | |
return lastName; | |
}); | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
resolve(`${capitalizedFirstName} ${capitalizedLastName}`); | |
}, 500); | |
}); | |
} | |
async function print(firstName, lastName) { | |
let name = await createName(firstName, lastName); | |
console.log(`Name: ${name}`); | |
} | |
print('john', 'doe'); | |
async function print(firstName, lastName) { | |
let name = await createName(firstName, lastName); | |
console.log(`Name: ${name}`); | |
} | |
print('john', 'doe'); // Will not log any errors. | |
print('John', 'doe'); // Will cause an error to be logged. However it will not fail the program as the Promise rejection is handled. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment