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));
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"
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