Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatmap Promise in JS

This must have been asked before, but how do you flatten a promise in JS?

Something like this:

let justAPromise: Promise<something> = aPromise.flatMap( a => getAnotherPromise());

Or something like this:

let promiseOfPromise: Promise<Promise<something>> = aPromise.then( a => getAnotherPromise());
let justAPromise: Promise<something> = promiseOfPromise.flatten();

EDIT:

Clarification on what I mean by flattening a promise. I see a massive difference between the following two. The first is a promise of int, and the second is a promise of a promise of int:

Promise.resolve(23);

Promise.resolve("whatever").then(a => Promise.resolve(23));
like image 679
eddyP23 Avatar asked Aug 10 '18 06:08

eddyP23


Video Answer


1 Answers

Just chain your promises:

let justAPromise: Promise<something> = aPromise.then( a => getAnotherPromise());

The example below show you that it's flattend by this way:

var aPromise = new Promise(resolve => setTimeout(() => resolve("a"), 1000));
var getAnotherPromise = () => new Promise(resolve => setTimeout(() => resolve("another"), 1000));
var justAPromise = aPromise.then(a => getAnotherPromise());
justAPromise.then(res => console.log(res)); // <-- this print "another"
like image 81
Faly Avatar answered Oct 06 '22 15:10

Faly