tera_789
tera_789

Reputation: 529

"TypeError: Cannot read property 'then' of undefined" caused by shorthand arrow function form

I just noticed this weird thing. When I have this code, Atom JSCS linting does not give me any errors

findById: id => {
  new Promise((resolve, reject) => {
    Zone.findById(id)
    .then(data => {
      resolve(data);
    })
    .catch(err => {
      reject(new Error('Sorry...'));
    });
  });
},

but my server returns the following error:

TypeError: Cannot read property 'then' of undefined

When I add return to this line, my app runs normal:

return new Promise((resolve, reject) =>

It looks like my node server does not recognize the new syntax for functions. Is it because I need to use Babel? Or maybe I am completely on the wrong track...

P.S I referenced this Stack Overflow question to find out that I need to use return explicitly:

Upvotes: 1

Views: 529

Answers (3)

Piterden
Piterden

Reputation: 789

findById: (id) => Zone.findById(id)

Why don't you use this construction? It is already a promise!

Upvotes: 0

jman93
jman93

Reputation: 367

Remove the brackets around your promise so the promise can return the resolved value.

findById: id => new Promise((resolve, reject) => {
      Zone.findById(id)
        .then(data => {
          resolve(data);
        })
        .catch(err => {
          reject(new Error('Sorry...'));
        });
    }

Also make sure that Zone.findById() always returns a Promise

Upvotes: 1

snak
snak

Reputation: 6703

Remove the brackets around the function body. The function returns undefined if you place brackets.

(() => { 1 })();
// undefined

(() => 1)();
// 1

Upvotes: 1

Related Questions