我正在尝试将承诺链 .then().catch 转换为异步/等待函数
const chain = [
{
onFulfilled: () => {/*some logic*/},
onRejected: () => {/*some logic*/},
{
onFulfilled: () => {/*some logic*/},
onRejected: () => {/*some logic*/},
{
onFulfilled: () => {/*some logic*/},
onRejected: () => {/*some logic*/},
},
//...
];
const data = 'initial data';
let promise = Promise.resolve(data);
let i = 0;
while (i < chain.length) {
promise = promise.then(chain[i].onFulfilled).catch(chain[i].onRejected);
i++;
}
最终承诺等于:
promise = Promise.resolve()
.then(chain[0].onFulfilled).catch(chain[0].onRejected)
.then(chain[1].onFulfilled).catch(chain[1].onRejected)
.then(chain[2].onFulfilled).catch(chain[2].onRejected)
....
这是我到目前为止尝试过的
let data = 'initial data';
for (const fn of chain) {
try {
data = await fn.onFulfilled(data);
} catch (e) {
data = await fn.onRejected(e);
}
}
问题是:如果 fn.onRejected 抛出一个错误,错误导致 for 循环停止而不是被下一个 fn.onRejected 处理
您可以使用
while
循环简化 for..of
混乱 -
let p = Promise.resolve(initialData)
for (const {onFulfilled, onRejected} of chain)
p = p.then(onFulfilled, onRejected)
与-
相同const p = chain.reduce(
(acc, {onFulfilled, onRejected}) =>
acc.then(onFulfilled, onRejected),
Promise.resolve(initialData)
)
我认为您为此使用
async..await
不会有任何收获。正如您已经指出的那样,由于try..catch
.,它引入了更多的复杂性