Javascript: Since use of 'ForOfStatement' is not allowed ...

Created on 6 Oct 2018  路  2Comments  路  Source: airbnb/javascript

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
    }  
}
question

All 2 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

brendanvinson picture brendanvinson  路  4Comments

stephenkingsley picture stephenkingsley  路  3Comments

felixsanz picture felixsanz  路  3Comments

kozhevnikov picture kozhevnikov  路  3Comments

mismith picture mismith  路  3Comments