我想做的事情:
我正在尝试创建一个函数来抽象它:
somePromise(options)
.then(anotherPromise)
.then(results =>
Promise.all(results.map(result =>
someOtherPromise(result.url)
.then(anotherPromise)
.then(val => Object.assign(val, { hello: "world" }))
)));
进入:
somePromise(options)
.then(anotherPromise)
.thenMapAll(results, result =>
someOtherPromise(result.url)
.then(anotherPromise)
.then(val => Object.assign(val, { hello: "world" }))
);
即抽象一个 .thenMapAll
函数,它代替 .then
将结果数组映射到 等待的 Promise 数组>Promise.all
.
到目前为止我所取得的成就:
这个:
Promise.mapAll = (array, fn) =>
Promise.all(array.map(val => fn(val)));
Promise.prototype.thenMapAll = (array, fn) =>
Promise.mapAll(array, val => fn(val));
这基本上有效!然而,Promise 的解决顺序并不正确。看起来 .thenMap
创建的 Promise 总是先于任何前面的 .then
创建的 Promise:
new Promise((res, rej) => res("a"))
.then(console.log) // Neither syntax makes a difference.
.then(() => new Promise((res,rej) => res(console.log("b"))))
.thenMapAll([ "c", "d", "e" ], console.log);
/* Outputs:
** c
** d
** e
** a
** b
*/
问题!
为什么 Promise 的顺序不正确?如何让 Promise 按正确的顺序运行?
最佳答案
thenMapAll
立即被调用,而不是将其 promise 添加到当前的 promise 链,您想要的是:
Promise.mapAll = (array, fn) =>
Promise.all(array.map(val => fn(val)));
Promise.prototype.thenMapAll = function(array, fn) {
return this.then(() => {
return Promise.mapAll(array, val => fn(val));
});
};
输出:
a
b
c
d
e
因为现在 thenMapAll
正在调用 this.then(() => {})
内部调用 Promise.mapAll
,即将其添加到现有的 promise 链中,而不是创建一个立即运行的全新 promise 链。由于我们要向 Promise.prototype 添加一个函数,因此 this
关键字引用当前的 Promise 实例,因此这就是我们被允许添加到 Promise 链的原因就这样。
关于javascript - 将 Promise 映射为 .then() 链的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44060329/