速记箭头功能形式

时间:2018-09-30 01:12:18

标签: javascript

我刚刚注意到了这件事。当我有这段代码时,Atom JSCS linting不会给我任何错误

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

但是,我的服务器返回以下错误:

  

TypeError:无法读取未定义的属性'then'

当我在此行中添加return时,我的应用将正常运行:

return new Promise((resolve, reject) =>

看来我的节点服务器无法识别函数的新语法。是因为我需要使用Babel吗?也许我完全走错了路...

P.S我引用了this堆栈溢出问题以发现我需要显式使用return

3 个答案:

答案 0 :(得分:1)

卸下功能主体周围的括号。如果放置括号,该函数将返回undefined

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

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

答案 1 :(得分:1)

删除承诺中的括号,以便承诺可以返回已解决的值。

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

还要确保Zone.findById()始终返回Promise

答案 2 :(得分:0)

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

您为什么不使用这种结构?已经是一个承诺!

相关问题