如何在此过滤器序列中添加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);
答案 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([{ }, { }]);