Ad

Can An Async Function Return Undefined Instead Of A Promise

I am working on an app using nodejs. I am making multiple HTTP requests with an async function and axios library. However I do not always want to return the fetched data from my http request, only if a certain condition is met.

Like so.

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
}

Then I am getting all the promises returned in an array with 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 ;
}

Then I get all the data

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

Here is my problem, when I get the returned data from getAllData, there is some undefined element because at the first function in the beginning (getFooHTTP) was returning nothing. My question is how can I return promises conditionally, so I don't get undefined promises returned even If the async function have no return statement.

Thank you

Ad

Answer

An async function will always return a Promise, no matter what. If you explicitly return a non-Promise even if there are no awaits before it, it will be automatically wrapped in a Promise before returning (eg return undefined will turn into something like return Promise.resolve(undefined)).

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

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

If you don't want to return values that don't fulfill condition, filter the Promise.all before returning it:

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
};

and

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 ;
};

Though, this relies on all of the Promises that getFooHTTP resolves to returning non-undefined values.

Ad
source: stackoverflow.com
Ad