Last active
August 29, 2015 14:01
-
-
Save azu/1e66a42cf90e37c0c296 to your computer and use it in GitHub Desktop.
Promise sequence - https://github.com/azu/promises-book/issues/46
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
"use strict"; | |
var assert = require("power-assert"); | |
var sequence = require("../lib/promise-sequence").sequencePromises; | |
describe("promise-sequence", function () { | |
it("should sequence promises", function () { | |
var promisedIdentity = [1, 2, 4, 8, 16, 32].map(function (value) { | |
return function identify() { | |
return new Promise(function (resolve) { | |
setTimeout(function () { | |
resolve(value); | |
}, value); | |
}) | |
} | |
}); | |
var startDate = Date.now(); | |
return sequence(promisedIdentity).then(function (values) { | |
console.log(Date.now() - startDate + "ms");// 約64ms | |
assert.deepEqual(values, [1, 2, 4, 8, 16, 32]); | |
}); | |
}); | |
}); |
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
"use strict"; | |
function sequencePromises(promises) { | |
var results = []; | |
var pushResult = Array.prototype.push.bind(results); | |
return promises.reduce(function (prevPromise, promisedIdentity) { | |
return prevPromise.then(function () { | |
return Promise.resolve(promisedIdentity()).then(pushResult); | |
}); | |
}, Promise.resolve()).then(function () { | |
return results; | |
}); | |
} | |
module.exports.sequencePromises = sequencePromises; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment