Promise.all获取JSON数据为空



在我的代码中,我试图从两个JSON文件中获取数据,并将它们作为数组返回。我做了下面的解决方案,但没有成功。我应该怎么做才能将这些阵列登录到控制台并实现我想要的目标?

TS:

requests = [
'data/products.json',
'data/categories.json',
];
constructor(private _http: HttpClient) {
const x = Promise.all(this.requests.map((url) => fetch(url))).then(
async (res) => Promise.all(res.map(async (data) => await data.json()))
);
console.log(x);
}

Promise.all的结果是"空";(从技术上讲是Promise(,因为在您登录时它还没有解决。您应该await它或在.then捕获结果。

我会在方法的构造函数之外将其重写为const x = await Promise.all(...),或者使用Promise.all(...).then(...)

使用那些毫无意义的async使代码过于复杂

问题是,x是一个承诺。。。在你安慰时未解决的承诺。将其记录为

尝试以下

requests = [
'data/products.json',
'data/categories.json',
];
constructor(private _http: HttpClient) {
const makeRequest = (url) => fetch(url).then(response => response.json());

Promise.all(this.requests.map(this.makeRequest))
.then(x => console.log(x));
}

最新更新