JS中的Flatmap Promise

8

这可能已经被问过了,但是如何在JS中展平promise呢?

像这样:

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

或者类似于这样的内容:

或者类似于这样:

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

编辑:

我所说的扁平化promise是什么意思需要澄清。我认为以下两者之间存在巨大差异:第一种是int类型的promise,而第二种是int类型的promise的promise:

Promise.resolve(23);

Promise.resolve("whatever").then(a => Promise.resolve(23));

你不能展开 Promises,只能展开数组,我不确定你具体想要什么? - CertainPerformance
1
.then() 实际上是 Promise 上的 .flatmap(),它还有一些额外的功能,例如在返回值不是 Promise 时自动将其包装为 Promise、捕获和包装异常等。 - Zoltan.Tamasi
1个回答

13

只需链接您的Promise:

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

以下示例显示通过此方式进行平面化:

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"


2
不,这不是一个 Promise<Promise<something>>。justPromise 现在是 getAnotherPromise 的返回值。 - Faly
1
在 then 回调中返回 somethingsomething 的 promise 都无所谓,它们总是会被平铺(flatten)。 - Faly
6
是的,如果你返回另一个 Promise 或任何其他类型的值,.then() 的工作方式会有所不同。 - skyboyer
2
谢谢,又是一些意想不到的 JS 魔法 :) 其他语言不会像它一样为你展开。 - eddyP23
@eddyP23 在这里查看: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/then 它说如果你传递的参数不是一个函数,它将被内部替换为“Identity”函数(它返回接收到的参数)。因此,如果您传递Promise(或任何非函数内容),它将仅返回其本身(在这种情况下为Promise)。 - SwiftMango
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接