Skip to content

Instantly share code, notes, and snippets.

@Zodiase
Last active April 4, 2016 20:41
Show Gist options
  • Save Zodiase/408b8cfa245b2d3699c21d3bb0d7c118 to your computer and use it in GitHub Desktop.
Save Zodiase/408b8cfa245b2d3699c21d3bb0d7c118 to your computer and use it in GitHub Desktop.
Examples of using Promise.
// Start from a Promise.
var foo = new Promise(function (resolve, reject) {
// Has to resolve to run callbacks in `.then()`.
resolve(1);
});
foo.then(function (result) {
// Received final resolve value from the Promise.
// result === 1;
console.log('result 1', result);
// Returned value is passed to the callback in the next `.then()`.
return result + 1;
}).then(function (result) {
// Received final resolve value from the Promise in the callback in the previous `.then()`.
// result === 2;
console.log('result 2', result);
});
foo.then(function (result) {
// Received final resolve value from the Promise.
// result === 1;
console.log('result 3', result);
// Returned value is passed to the callback in the next `.then()`.
return result + 1;
}).then(function (result) {
// Received final resolve value from the Promise in the callback in the previous `.then()`.
// result === 2;
console.log('result 4', result);
});
// Output:
// result 1 1
// result 3 1
// result 2 2
// result 4 2
// Start from a Promise.
(new Promise(function (resolve, reject) {
// Has to resolve to run callbacks in `.then()`.
resolve(
// Pass another Promise as the resolve value to wait for the fulfillment of that Promise.
new Promise(function (resolve, reject) {
// Final resolve value will be passed to the callback in the next `.then()`.
resolve(1);
})
);
})).then(function (result) {
// Received final resolve value from the Promise.
// result === 1;
console.log('result', result);
// Returned value is passed to the callback in the next `.then()`.
return result + 1;
}).then(function (result) {
// Received return value from the previous callback in `.then()`.
// result === 2;
console.log('result', result);
return new Promise(function (resolve, reject) {
// Final resolve value will be passed to the callback in the next `.then()`.
resolve(result + 1);
});
}).then(function (result) {
// Received final resolve value from the Promise in the callback in the previous `.then()`.
// result === 3;
console.log('result', result);
});
// Output:
// result 1
// result 2
// result 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment