Last active
June 5, 2019 11:22
-
-
Save jagomf/c8989388b14294db7bbcecdcf28f079b to your computer and use it in GitHub Desktop.
Promises to async/await
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 with a promise | |
const doAsyncStuff = () => { | |
return new Promise((resolve, reject) => { | |
if (stuff) { | |
resolve('cool'); | |
} | |
reject('bad'); | |
}); | |
}; | |
// Promise function resolution, old style | |
main() { | |
doAsyncStuff().then(res => { | |
// res === 'cool' | |
}).catch(err => { | |
// err === 'bad' | |
}); | |
} | |
// Promise function resolution, async/await style | |
async main() { | |
try { | |
const isCool = await asyncStuff(); | |
// isCool === 'cool' | |
} catch (err) { | |
// err === 'bad' | |
} | |
} |
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
// Inline promise resolution, old style | |
main() { | |
new Promise((resolve, reject) => { | |
if (stuff) { | |
resolve('cool'); | |
} | |
reject('bad'); | |
}).then(res => { | |
// res === 'cool' | |
}).catch(err => { | |
// err === 'bad' | |
}); | |
} | |
// Inline promise resolution, async/await style | |
async main() { | |
const asyncStuff = () => new Promise((resolve, reject) => { | |
if (stuff) { | |
resolve('cool'); | |
} | |
reject('bad'); | |
}); | |
try { | |
const isCool = await asyncStuff(); | |
// isCool === 'cool' | |
} catch (err) { | |
// err === 'bad' | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment