可以使用未定义的异步函数 return 而不是 Promise

Can an async function return undefined instead of a Promise

我正在使用 nodejs 开发一个应用程序。我正在使用异步函数和 axios 库发出多个 HTTP 请求。但是,我并不总是希望 return 从我的 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
}

然后我得到所有的承诺 returned 在数组中 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 获取 returned 数据时,有一些未定义的元素,因为在开头的第一个函数 (getFooHTTP) 是 return什么都没有。我的问题是我如何 return 有条件地承诺,所以即使异步函数没有 return 语句,我也不会得到未定义的承诺 returned 。

谢谢

一个async函数将总是return一个Promise,无论如何。如果你显式 return 一个非 Promise,即使它之前没有 awaits,它也会在 returning 之前自动包装在一个 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);

如果您不想 return 不满足 condition 的值,filter Promise.all 在 return 之前:

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 解析为 return 非 undefined 值的所有 Promise。