相关疑难解决方法(0)

使用返回promise的函数过滤数组

特定

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用于特定代码.

javascript arrays ecmascript-6 es6-promise

49
推荐指数
8
解决办法
4万
查看次数

如果filter函数是异步的,如何使用lodash过滤列表

我对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过滤器函数中执行此操作?提前致谢。

javascript node.js lodash

5
推荐指数
1
解决办法
5030
查看次数

标签 统计

javascript ×2

arrays ×1

ecmascript-6 ×1

es6-promise ×1

lodash ×1

node.js ×1