首页 > 解决方案 > 异步函数可以返回 undefined 而不是 Promise

问题描述

我正在使用 nodejs 开发一个应用程序。我正在使用异步函数和 axios 库发出多个 HTTP 请求。但是,我并不总是希望从我的 http 请求中返回获取的数据,只有在满足特定条件的情况下。

像这样。

const getFooHTTP = async (id) => {
let response = await axios.get(url);

if (condition){
//I only want to return the response here
return response;
}

//Here i do not want to return the response
}

然后我得到一个数组中返回的所有承诺Promise.all()

const getAllData = async() => {
let dataArray = [];
for (let i = 0; i < n; i++){
const data = getFooHTTP(i);
dataArray.push(data)
}
const someData = await Promise.all(dataArray);
return someData ;
}

然后我得到所有数据

getAllData().then(data => {
//Here is the problem, here I get a bunch of undefined in my data array
console.log(data);
})

这是我的问题,当我从 获取返回的数据时getAllData,有一些未定义的元素,因为在开头的第一个函数 ( getFooHTTP) 没有返回任何内容。我的问题是如何有条件地返回承诺,所以即使异步函数没有返回语句,我也不会返回未定义的承诺。

谢谢

标签: javascriptnode.jsasync-awaites6-promise

解决方案


无论如何,一个async函数总是会返回一个 Promise。如果你显式地返回一个非 Promise,即使await它之前没有 s,它会在返回之前自动包装在一个 Promise 中(例如return undefined会变成类似的东西return Promise.resolve(undefined))。

const prom = (async () => {
  return undefined;
})();

// Even though it returned undefined, it's still a Promise:
console.log(typeof prom.then);

如果您不想返回不满足的值,conditionfilterPromise.all返回之前:

const getFooHTTP = async (id) => {
  let response = await axios.get(url);
  if (condition){
    //I only want to return the response here
    return response;
  }
  //Here i do not want to return the response
  return undefined;
  // or, have no return statement at all
};

const getAllData = async() => {
  let dataArray = [];
  for (let i = 0; i < n; i++){
    const data = getFooHTTP(i);
    dataArray.push(data)
  }
  const someData = (await Promise.all(dataArray))
      .filter(val => val !== undefined);
  return someData ;
};

但是,这依赖于所有getFooHTTP解析为返回非undefined值的 Promise。


推荐阅读