javascript - 异步函数可以返回 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
) 没有返回任何内容。我的问题是如何有条件地返回承诺,所以即使异步函数没有返回语句,我也不会返回未定义的承诺。
谢谢
解决方案
无论如何,一个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);
如果您不想返回不满足的值,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
值的 Promise。
推荐阅读
- python - 如何使用行为框架中的夹具保持 selenium webdriver 作为 before_tag 钩子的一部分运行?
- php - 用户提交答案后,有没有办法将测试表的答案复制到 pdf 中?
- sql - 在 SQL 的列中查找字符串/整数中的最大值
- r - 从数据框列表中提取并组合具有相同名称的列
- python - 如何仅使用用户输入移动矩阵中的项目?
- ios - MPSMatrixVectorMultiplication 太慢了
- android - Android WebView 仅适用于 API 28
- javascript - Javascript 获取正文 JSON 列表
- python - Anaconda:Python 是 64 位,numpy 是 32 位 -> 冲突。如何获得 numpy 64 位
- jquery - “阅读更多”产品类别描述的 Jquery 功能未按预期工作