Skip to content

Instantly share code, notes, and snippets.

@ivawzh
Last active April 26, 2016 14:20
Show Gist options
  • Save ivawzh/3cc297413f7979cd870fd859ffcebc53 to your computer and use it in GitHub Desktop.
Save ivawzh/3cc297413f7979cd870fd859ffcebc53 to your computer and use it in GitHub Desktop.
when is a promise triggered?
// Promise is triggered by `()`, not `.then()`
describe('promise trigger', () => {
it('flat promise is triggered by `()` even without .then', done => {
let result = []
result.push(1)
function aFlatPromise(val) {
return new Promise(resolve => {
result.push(val)
resolve(val)
})
}
result.push(2)
const array = [aFlatPromise('a')] // <--------------- suprise! this triggers the promise
result.push(3)
array[0].then(()=>{
result.push(4)
expect(result).to.eql([ 1, 2, 'a', 3, 4 ])
done()
})
})
})
// http://stackoverflow.com/questions/36864780/execute-an-array-of-javascript-promises-one-after-one-resolved
import Promise from 'bluebird'
describe('promises waterfall', () => {
const result = []
function doItLater(val, time = 50) => {
return new Promise(resolve => {
setTimeout(() => {
result.push(val)
resolve(val)
}, time)
})
}
it('execute promises one after one resolved', done => {
result.push(1)
const promiseList = [doItLater('a', 100),doItLater('b', 1),doItLater('c')]
result.push(2)
Promise.each(
promiseList,
(output) => {
result.push(output + '-outputted')
}
)
.then(
() => {
result.push(3)
console.log(result)
expect(result).to.eql([ 1, 2, 'a', 'b', 'c', 'a-outputted', 'b-outputted', 'c-outputted', 3 ])
done()
}
)
})
})
// How is a promise triggered? Is it triggered by () or by .then()? Because if the promises are executed when I assign them to array [doItLater('a', 100),doItLater('b', 1),doItLater('c')] as you said, then shouldn't the actual result have each of the 'a', 'b' and 'c' appears twice? e.g. something like [1, b, c, a, 2, b, c, a, ...], because I have executed the promises twice? – Ivan Wang 53 mins ago
// When you do doItLater('a', 100), the async operation starts and the promise object is returned. So when you do promiseList, we are simply dealing with the promise objects returned by doItLater, the async operations are not triggered again. – thefourtheye 50 mins ago
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment