简体   繁体   中英

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

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(.........)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM