重试承诺步骤 [英] Retry a promise step
问题描述
假设我有以下Promise链:
Suppose I have the the following Promise chain:
var result = Promise.resolve(filename)
.then(unpackDataFromFile)
.then(transformData)
.then(compileDara)
.then(writeData);
现在,我不仅有一个 transformData
函数,而且还有两个或多个存储在数组中的函数.我想尝试第一个,如果 compileData
函数失败,请尝试第二个,依此类推,直到 compileData
成功或 transformData的数组
函数已用尽.
Now I have not only one transformData
function but two or more, stored in an array. I want to try the first one, and if the compileData
function fails, try the second one and so on until either compileData
succeeds or the array of transformData
functions is exhausted.
有人可以举一个例子来说明如何实现吗?
Can someone give me an example on how to implement this?
运行所有 transformData
函数并将结果数组提供给 compileData
并不是一种选择,因为这些函数非常昂贵,并且我想运行尽可能少的函数.
Running all transformData
functions and give the result array to compileData
is not an option, since the functions are very expensive and I want to run as few as possible of them.
transformData
本身也会返回Promise.
transformData
itself also returns a Promise, if that helps.
推荐答案
我将首先隔离尝试多个promise直到成功的概念:
I would start by isolating the notion of trying a number of promises until one succeeds:
function tryMultiple([promise, ...rest]) {
if (!promise) throw new Error("no more to try");
return promise.catch(() => tryMultiple(rest));
}
现在编写一个处理程序,尝试处理转换和编译的每种组合:
Now write a handler which tries each combination of transforming and compiling:
function transformAndCompile(transformers) {
return function(data) {
return tryMultiple(transformers.map(t => t(data).then(compileData)));
};
}
现在最高级是:
var result = Promise.resolve(filename)
.then(unpackDataFromFile)
.then(transformAndCompile(transformers))
.then(writeData);
顺便说一句, Promise.resolve(filename).then(unpackDataFromFile)
只是一种回旋方式,它表示 unpackDataFromFile(filename)
.
By the way, Promise.resolve(filename).then(unpackDataFromFile)
is just a roundabout way of saying unpackDataFromFile(filename)
.
这篇关于重试承诺步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!