最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Flatmap Promise in JS - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 13

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"

发布评论

评论列表(0)

  1. 暂无评论