Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening promises in javascript

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.

like image 705
George Simms Avatar asked Jun 28 '15 19:06

George Simms


People also ask

What is the problem with promises in Javascript?

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".

How do you handle promise rejection?

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.

How do you resolve a promise with await?

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.

Are Javascript promises lazy?

As soon as the javascript Interpreter sees a promise declaration. It immediately executes its implementation synchronously. Even though it will get settled eventually.


1 Answers

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.

like image 111
Bergi Avatar answered Oct 05 '22 23:10

Bergi