删除返回未定义的承诺



我试图弄清楚如何过滤通过Promise.lose.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)))
.then(allData => console.log(allData)) // How can I get rid of the undefined values BEFORE it gets here?

您可以在Promise.all之后插入另一个.then调用以过滤数组。没有其他方法,您不能在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?

最新更新