Skip to content

Instantly share code, notes, and snippets.

@scottgreenup
Created October 10, 2017 00:39
Show Gist options
  • Save scottgreenup/9917bc986350e37130114658b758b86a to your computer and use it in GitHub Desktop.
Save scottgreenup/9917bc986350e37130114658b758b86a to your computer and use it in GitHub Desktop.
ES6 Promise Example
/*
$ node promises.js
1: Hello
2: Hello, world
3: Hello, world. I am a Promise.
4: Error: REJECTION!
*/
const assert = require('assert')
new Promise((resolve, reject) => {
// Some asynchronous object that will eventually resolve
setTimeout(() => {
resolve('Hello')
}, 300);
}).then(result => {
// We will get 'Hello'
assert.strictEqual(result, 'Hello')
console.log(`1: ${result}`)
// Now we can chain a result, if we want
return result + ', world'
}).then(result => {
// We will get 'Hello, world'
assert.strictEqual(result, 'Hello, world')
console.log(`2: ${result}`)
// We can continue this chain, and it can either be a random value, or a
// Promise, so let's return a Promise.
return new Promise((resolve, reject) => {
resolve(`${result}. I am a Promise.`)
})
}).then(result => {
// Note how the result is not a Promise,
// but is 'Hello, world. I am a Promise.'
// This is because the Promise is resolved before this callback is called,
// and this callback is called with the value that was resolved.
assert.strictEqual(result, 'Hello, world. I am a Promise.')
console.log(`3: ${result}`)
// Now, we could also reject. whe
return new Promise((resolve, reject) => {
reject(new Error("REJECTION!"))
})
}).then(result => {
assert.fail("I should never be called")
}).then(result => {
assert.fail("Neither will I")
}).catch(error => {
// The previous two are skipped because of the reject.
console.log(`4: ${error}`)
assert.strictEqual(error.message, "REJECTION!")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment