For a function fnthat returns a promise and an array of arbitrary data length (for example data = ['apple', 'orange', 'banana', ...]), how do you bind function calls for each element of the array sequentially, so if it fn(data[i])resolves, the whole chain ends and stops the call fn, but if it is fn(data[i])rejected, the next call fn(data[i + 1])is made?
Here is a sample code:
const fn = datum =>
new Promise((resolve, reject) => {
console.log(`trying ${datum}`);
if (Math.random() < 0.25) {
resolve(datum);
} else {
reject();
}
});
const foundResult = result => {
console.log(`result = ${result}`);
};
const data = ['apple', 'orange', 'banana', 'pineapple', 'pear', 'plum'];
fn('apple').then(foundResult)
.catch(() => {
fn('orange').then(foundResult)
.catch(() => {
fn('banana').then(foundResult)
.catch(() => {
});
});
});
I feel that maybe there is an elegant solution to this model that I am missing. The behavior is very similar to Array.some(), but I came empty trying to play with it.
EDIT: I switched from numeric data to string to emphasize that the solution should not rely on numeric data.
# 2: , fn , . fn , . fn - API, ..