Last active
March 14, 2018 23:37
-
-
Save Synvox/9b8584fc7b64e46cdc450ecc371098ab to your computer and use it in GitHub Desktop.
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
// PROMISES! | |
// There are two ways to work with promises. | |
// Option 1 the easiest once you understand it. | |
// JavaScript has a feature called Async-Await | |
// Notice the *async* keyword before function | |
async function asyncPattern() { | |
// In async functions, you can get the result of | |
// promises without .then. Just stick a 'await' | |
// in front of it and it will wait for the promise | |
// to get it's result. | |
const four = await promiseAdd(2, 2) | |
console.log('async 2 + 2 = ' + four) | |
// You can do await <promise> as many times as you'd like. | |
const eight = await promiseAdd(4, 4) | |
console.log('async 4 + 4 = ' + eight) | |
} | |
// Note: | |
// async functions return promises too. | |
// Option 2 | |
promiseAdd(2, 2).then((four)=>{ | |
// When the promise finishes, the result comes in as | |
// the first argument (in this case, four) | |
console.log('2 + 2 = ' + four) | |
}).catch((error)=>{ | |
// If an error occurs in the promise, this will fire | |
console.log(error) | |
}) | |
// Important note: | |
// Do NOT call .then in a .then function. It is a quick | |
// way to get a bug. | |
promiseAdd(2, 2).then((four)=>{ | |
// Instead, return your promise inside of the 'then' | |
// funcition like so: | |
return promiseAdd(four, four) // essentially 4 + 4 | |
// Returning a value from a promise creates another | |
// promise, to which you can call .then again. | |
}).then((eight)=>{ | |
// The result of the previous promise comes in like | |
// normal. | |
console.log('4 + 4 = ' + eight) | |
}).catch((error)=>{ | |
// If an error occurs in any of the promises, it will | |
// be given here. | |
console.log(error) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment