【发布时间】: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