将异步/等待添加到一系列JS过滤器

时间:2018-11-12 20:54:44

标签: javascript

如何在此过滤器序列中添加async和await以确保在调用下一个过滤器之前返回一个过滤器的结果?

let rooms = [
  {
    type: "bedroom",
    name: "Caroline",
    utility: {
      size: "90-150",
      shape: "square",
    }

let hasType = async (type, object) => object.type === type;
let resultType = rooms.filter(x => hasType("bedroom", x));
console.log(resultType);

let hasSize = (size, object) => object.utility.size === size;
let resultTypePlusSize = resultType.filter(x => hasSize("90-150", x));
console.log(resultTypePlusSize);

let hasShape = (shape, object) => object.utility.shape === shape;
let resultTypePlusSizePlusShape = resultTypePlusSize.filter(
  x => hasShape("square", x));
console.log(resultTypePlusSizePlusShape);

1 个答案:

答案 0 :(得分:0)

您可以使用reduce建立承诺链,然后使用Promise.all执行多个:

 function chain(...mappers) {
   return {
    exec(start) {
      return mappers.reduce((value, fn) => {
        if(value instanceof Promise) {
           return value.then(fn);
        } else {
           return fn(value);
        }
      }, start);
    },
    many(values) {
      return Promise.all(values.map(val => this.exec(val)));
    }
  };
}

用作:

 const transformUsers = chain(
   user => (user.name = "test", user),
   async user => user.name,
   console.log
);

transformUsers.many([{ }, { }]);