arv*_*tal 0 javascript typescript
很多时候我问自己同样的问题......用JS编写相当直接的代码的所有语法(并不总是直观),我想知道,有人会知道这种操作的单线程吗?
var setFeatured = entry => {
entry.isFeatured = true;
return entry
}
SomeCallThatReturnsAPromise.then(entries => entries.map(setFeatured))
Run Code Online (Sandbox Code Playgroud)
要分配一个属性并一次性返回该对象,我可以直接将其作为arg的可读方式放入 entries.map
为了给出一个关于什么是向我求婚了反馈,共同的答案是用OR运算符返回结果,分配或函数调用后(返回undefined,null,false,never,以及任何将触发或之后的部分):
return entry.isFeatured = true || entry
我的问题是要知道我是否可以利用更紧凑的语法:
SomeCallThatReturnsAPromise()
.then((entries:EntryType[]) => entries
.map(entry => entry.isFeatured = true || entry)
.filter(entry => entry.something == true))
.then((entries:EntryType[]) => someCallThatReturnsNothingButHasToBeDoneThere() || entries)
.then((entries:EntryType[]) => console.log(entries))
Run Code Online (Sandbox Code Playgroud)
会更容易阅读:
SomeCallThatReturnsAPromise
.then((entries:EntryType[]) => entries
.map(entry => {
entry.isFeatured = true;
return entry;
})
.filter(entry => entry.something == true))
.then((entries:EntryType[]) => {
someCallThatReturnsNothingButHasToBeDoneThere();
return entries;
})
.then((entries:EntryType[]) => console.log(entries))
Run Code Online (Sandbox Code Playgroud)
笔记:
1)我尽量避免为此创建一个函数.我的问题是出于好奇心,只关注Vanilla ES6或7语法提供的内容.
2)我被回答使用.forEach而不是.map.我使用函数方法设计我的代码(因此紧凑回调的重要性),因此.forEach对我来说不一定是一个好的选择(显然它在性能或内存消耗方面没有优于map的优势).在处理promises回调或数组函数链时,单行语法都很方便...
3)使用OR运算符时返回的类型是union类型,EntryType|null.因此它打破了后续调用的类型,并暗示了一个类型断言:
SomeCallThatReturnsAPromise()
.then((entries:EntryType[]) => entries
.map(entry => (entry.isFeatured = true || entry) as EntryType)
.filter(entry => entry.something == true))
.then((entries:EntryType[]) => (someCallThatReturnsNothingButHasToBeDoneThere() || entries) as EntryType[])
.then((entries:EntryType[]) => console.log(entries))
Run Code Online (Sandbox Code Playgroud)
那变得越来越重了......我仍然不知道我是否会使用它或坚持两行,包括return语句.
4)这是一个简化的例子.我知道我的第一个then包含同步调用或者我的示例可能更准确.
entries.forEach( (entry) => entry.isFeatured = true );
Run Code Online (Sandbox Code Playgroud)
无需单独定义功能.
此外,由于您的元素是对象并且通过引用处理,因此可以替换map()为forEach(),这消除了返回值的必要性.(使用map()你最终将得到两个由相同元素组成的数组,可能不是,你需要什么)
| 归档时间: |
|
| 查看次数: |
1967 次 |
| 最近记录: |