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.
Apart from how the API is structured - promises have another major flaw: they treat unintentional native runtime exceptions and intentional rejected promises - which are two drastically different intentions - in the same "path".
If an error condition arises inside a promise, you “reject” the promise by calling the reject() function with an error. To handle a promise rejection, you pass a callback to the catch() function. This is a simple example, so catching the rejection is trivial.
Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
As soon as the javascript Interpreter sees a promise declaration. It immediately executes its implementation synchronously. Even though it will get settled eventually.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With