admin管理员组

文章数量:1289506

The bluebird library seems to automagically use Promise::then both as an equivalent of "map" and "flatMap" on the promise, eg see this example.

var Promise;

Promise = require('bluebird').Promise;

Promise.resolve(1).then(function(x) {
  return Promise.resolve(x + 1);
}).then(function(x) {
  return console.log(x); // => `2` (not a promise)
});

Promise.resolve(1).then(function(x) {
  return x + 1;
}).then(function(x) {
  return console.log(x); // => `2`
});

Promise.reject('hi').catch(function(x) {
  return Promise.reject('hi2');
}).catch(function(x) {
  return console.error(x); //  => `hi2` (not a promise)
});

Is this a contract of the es6 Promise API? I see no mention of this flattening behavior here or here, for example.

The bluebird library seems to automagically use Promise::then both as an equivalent of "map" and "flatMap" on the promise, eg see this example.

var Promise;

Promise = require('bluebird').Promise;

Promise.resolve(1).then(function(x) {
  return Promise.resolve(x + 1);
}).then(function(x) {
  return console.log(x); // => `2` (not a promise)
});

Promise.resolve(1).then(function(x) {
  return x + 1;
}).then(function(x) {
  return console.log(x); // => `2`
});

Promise.reject('hi').catch(function(x) {
  return Promise.reject('hi2');
}).catch(function(x) {
  return console.error(x); //  => `hi2` (not a promise)
});

Is this a contract of the es6 Promise API? I see no mention of this flattening behavior here or here, for example.

Share Improve this question edited Jun 28, 2015 at 19:55 George Simms asked Jun 28, 2015 at 19:48 George SimmsGeorge Simms 4,0604 gold badges23 silver badges36 bronze badges 1
  • Uh, those docs are very sparse. MSDN doesn't even mention that then returns a promise :-/ – Bergi Commented Jun 28, 2015 at 20:54
Add a ment  | 

1 Answer 1

Reset to default 13

Is this a contract of the es6 Promise API?

Yes, it is a contract established by Promises/A+, and has made its way from there into the ES6 specification. You will find some discussions here, here and here.

本文标签: Flattening promises in javascriptStack Overflow