【发布时间】:2018-02-11 01:16:37
【问题描述】:
给定一个函数fn,它返回一个promise,以及一个任意长度的数据数组(例如data = ['apple', 'orange', 'banana', ...]),你如何按顺序对数组的每个元素进行函数调用,这样如果fn(data[i])解决,整个链完成并停止调用fn,但如果fn(data[i]) 拒绝,下一个调用fn(data[i + 1]) 执行?
这是一个代码示例:
// this could be any function which takes input and returns a promise
// one example might be fetch()
const fn = datum =>
new Promise((resolve, reject) => {
console.log(`trying ${datum}`);
if (Math.random() < 0.25) {
resolve(datum);
} else {
reject();
}
});
const foundResult = result => {
// result here should be the first value that resolved from fn(), and it
// should only be called until the first resolve()
console.log(`result = ${result}`);
};
// this data can be purely arbitrary length
const data = ['apple', 'orange', 'banana', 'pineapple', 'pear', 'plum'];
// this is the behavior I'd like to model, only for dynamic data
fn('apple').then(foundResult)
.catch(() => {
fn('orange').then(foundResult)
.catch(() => {
fn('banana').then(foundResult)
.catch(() => {
/* ... and so on, and so on ... */
});
});
});
我觉得我缺少的这种模式可能有一个优雅的解决方案。该行为与Array.some() 非常相似,但我试图摆弄它是空的。
编辑:我从数字数据切换到字符串,以强调解决方案不需要依赖于数字数据。
编辑#2:为了进一步澄清,fn 可以是任何接受输入并返回承诺的函数。上面的fn 实现只是为了给出一个完整的例子。实际上,fn 实际上可能是 API 请求、数据库查询等。
【问题讨论】:
-
但是
fn总是在解决后返回一些东西,对吧? -
@emil 不一定,不。如果 promise 在没有数据的情况下解析,则
foundResult()中的result将只是undefined,这很好。
标签: javascript promise