Pretty sure this has been discussed thousands of times but haven't found a perfect replacement for my code snippet below.
Since the use of for...of construct is not allowed, how can I write following code?
// lines is an array of strings
let value = ''
for (const line of lines) {
try {
const json = JSON.parse(line)
if (json) {
value = json.whatever
/*
more logic irrelevant to this question
*/
// As soon as first jsonable line is found and processed, short-circuit the loop
break
}
} catch (err) {
// Handle error
// throw / reject / console.error() / return - could be anything
}
}
const value = lines.reduce((prev, line) => prev.then((lastValue) => {
if (lastValue) { return lastValue; }
const result = JSON.parse(line);
if (result) {
return value.whatever;
}
}).catch(errorHandling), Promise.resolve());
as long as errorHandling returns a falsy value to continue processing, a truthy value to stop processing, or re-throws, then value should end up as a promise for your desired value.
@ljharb Thank you.