Search code examples
javascriptpromiseecmascript-6es6-promise

Unexpected block statement surrounding arrow body Promise


I use React, ES6 and get following error message. I tried different stuff from here but its not working for me. If I remove "return" I get this error:

error Do not use 'new' for side effects no-new

If I code like this

const asyncValidate = (values, dispatch) => {
  const promise = new Promise(resolve, reject)
  promise()...

I cannot access resolve and reject of constructor.


Short

How to get this code working?

const asyncValidate = (values, dispatch) => {
  return new Promise((resolve, reject) => {
    validation.availableUserEmail(values.email, dispatch)
    .catch(err => reject(err));
  });
};

error Unexpected block statement surrounding arrow body arrow-body-style


Solution

  • Arrow functions can be shortened if you only have one expression, and you wish to return that expression, so for example, if you wanted a function to return the number you passed in + 1, this is a shortened version: x => x + 1.

    new Promise(............) is a single expression, and you want to return it, so you can (And should, which is why ESLint is complaining) shorten it like so:

    (values, dispatch) =>
      new Promise(...........)
    

    Moreover, since validation.availableUserEmail() returns a Promise itself, you can drop the Promise constructor altogether (wrapping a Promise with a Promise constructor is an antipattern), so you can simply do:

    (values, dispatch) =>
      validation.availableUserEmail(.......)
        .catch(.........)