特定
let arr = [1,2,3];
function filter(num) {
return new Promise((res, rej) => {
setTimeout(() => {
if( num === 3 ) {
res(num);
} else {
rej();
}
}, 1);
});
}
function filterNums() {
return Promise.all(arr.filter(filter));
}
filterNums().then(results => {
let l = results.length;
// length should be 1, but is 3
});
Run Code Online (Sandbox Code Playgroud)
长度为3,因为返回了Promises,而不是值.有没有办法用返回Promise的函数过滤数组?
注意:对于此示例,fs.stat已替换为setTimeout,请参阅https://github.com/silenceisgolden/learn-esnext/blob/array-filter-async-function/tutorials/array-filter-with-async- function.js用于特定代码.
我对lodash和Javascript还是陌生的。我正在使用nodejs。我正在使用lodash过滤器功能过滤集合中的某些内容。
这是片段
filteredrows = _.filter(rows, function(row, index){
//here I need to call some asynchronous function which checks the row
//the return value of this asynchronous function will determine whether to return true or false for the filter function.
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,我该怎么做?使用闭包?是否可以在lodash过滤器函数中执行此操作?提前致谢。