以前肯定有人问过这个问题,但是如何在 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.resolve(23);
Promise.resolve("whatever").then(a => Promise.resolve(23));
最佳答案
只需链接您的 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"
关于javascript - JS 中的平面图 promise ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51780681/