我试图弄清楚如何过滤掉通过Promise.all执行的promises并返回undefined。我在下面提供了一个例子。
我知道我可以在"然后"之后过滤掉它们。但是我想知道在它到达那一点之前是否可以删除它们。
// External Resource Such as Redis
const getDataFromExternalResource = (key) => {
const data = {
"a": "{val: 'valA'}",
"b": "{val: 'valB'}",
"d": "{val: 'valD'}",
}
return new Promise((resolve, reject) => {
resolve((data[key] ? data[key] : undefined))
})
}
// Look up Keys that may or may not return 'undefined'
const lookups = ['a', 'b', 'c'];
Promise
.all(lookups.map(key => getDataFromExternalResource(key)))
.then(allData => console.log(allData)) // How can I get rid of the undefined values BEFORE it gets here?

答案 0 :(得分:0)
您可以在.then
之后再插入一次Promise.all
调用来过滤数组。没有其他办法,您无法在Promise.all
中过滤。
// External Resource Such as Redis
const getDataFromExternalResource = (key) => {
const data = {
"a": "{val: 'valA'}",
"b": "{val: 'valB'}",
"d": "{val: 'valD'}",
}
return new Promise((resolve, reject) => {
resolve((data[key] ? data[key] : undefined))
})
}
// Look up Keys that may or may not return 'undefined'
const lookups = ['a', 'b', 'c'];
Promise
.all(lookups.map(key => getDataFromExternalResource(key)))
// <== next line is the inserted one ==>
.then(allData => allData.filter(x => x !== undefined))
.then(allData => console.log(allData)) // How can I get rid of the undefined values BEFORE it gets here?
&#13;