异步函数可以返回undefined而不是Promise吗

时间:2019-08-25 04:29:12

标签: javascript node.js async-await es6-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)中什么都没有返回。我的问题是如何有条件地返回承诺,因此即使异步函数没有return语句,我也不会得到未定义的承诺。

谢谢

1 个答案:

答案 0 :(得分:2)

无论如何,async函数都会始终返回Promise。如果即使之前没有await,也明确地返回了一个非承诺,则它会在返回之前自动包装在一个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);

如果您不希望返回不满足condition的值,请在返回filter之前先Promise.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值的所有承诺。