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));
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));
Share
Improve this question
edited Aug 10, 2018 at 7:02
eddyP23
asked Aug 10, 2018 at 6:55
eddyP23eddyP23
6,82511 gold badges57 silver badges98 bronze badges
2
- You can't flatten Promises, you can only flatten arrays, I'm not sure precisely what you're asking for..? – CertainPerformance Commented Aug 10, 2018 at 6:56
- 1 The .then() is actually the .flatmap() on the Promise with some extra stuff, like it wraps the returned value into Promise automatically when it wasn't, catches and wraps exception and etc. – Zoltan.Tamasi Commented Aug 10, 2018 at 7:14
1 Answer
Reset to default 13Just 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"