2016-07-26 201 views
-2

请解释这个JavaScript语言结构:JavaScript参数映射()函数

cursor => cursor.map(doc => doc._key) 

在这种情况下

collection.all().then(
    cursor => cursor.map(doc => doc._key) // this line 
).then(
    keys => console.log('All keys:', keys.join(', ')), 
    err => console.error('Failed to fetch all documents:', err) 
); 

不了解doc => doc._key作为参数传递给map()功能。为什么它不适用于doc => { key: doc._key, name: doc.name}

+1

看看术语箭头功能,这将回答你的问题。 – Christos

+0

谢谢Christos。我今天花了两个小时搜索,不知道他们被称为箭头函数。 –

回答

1

让我们按行划分: 也有一些documentation on arrow functions

collection.all() 

// give me all the documents in the collection 

.then(

    cursor 

// take a cursor, which goes over each item in the collection 

=> 

// you can think of this as "take the cursor as input into an anonymous function, and return..." 

cursor.map(

// a map over the cursors output 

doc => doc._key) 

// each document the cursor finds, return the documents key 

).then(

    keys => console.log('All keys:', keys.join(', ')), 

// take the resulting keys, and console log their value 

    err => console.error('Failed to fetch all documents:', err) 

// if there are any errors, please log those as well. 
); 
+0

非常感谢Patrick,很好的回答。现在我可能最终会重构很多代码:)) –

+0

当然!没问题。尽管如此,请小心阅读文档。有一些主要的问题,包括兼容性,以及上下文中“this”的含义。除此之外,这是一个非常令人敬畏的IMO语法。 –

+0

是的,先生,确实如此。看起来我不得不再花几天的时间阅读,然后才跳入node.js。 –