【问题标题】:Can an async function return undefined instead of a Promise [duplicate]异步函数能否返回 undefined 而不是 Promise [重复]
【发布时间】:2019-12-29 18:42:58
【问题描述】:

我正在使用 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 返回到一个带有 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) 没有返回任何内容。我的问题是如何有条件地返回承诺,所以即使异步函数没有返回语句,我也不会返回未定义的承诺。

谢谢

【问题讨论】:

标签: javascript node.js async-await es6-promise


【解决方案1】:

async 函数将始终返回一个 Promise,无论如何。如果你显式返回一个非 Promise,即使它之前没有 awaits,它会在返回之前自动包装在一个 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。

【讨论】:

    猜你喜欢
    • 2021-06-05
    • 2018-07-09
    • 2016-01-10
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多