How to return the Promise.all fetch api json data?(如何返回 Promise.all 获取 api json 数据?)
问题描述
如何使用 Promise.all 获取 api json 数据?如果我不使用 Promise.all,它可以正常工作.使用 .all 它实际上会在控制台中返回查询的值,但由于某种原因我无法访问它.这是我的代码以及它解析后在控制台中的外观.
How to I consume the Promise.all fetch api json data? It works fine to pull it if I don't use Promise.all. With .all it actually returns the values of the query in the console but for some reason I'm not able to access it. Here is my code and how it looks in the console after it resolves.
Promise.all([
fetch('data.cfc?method=qry1', {
method: 'post',
credentials: "same-origin",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: $.param(myparams0)
}),
fetch('data.cfc?method=qry2', {
method: 'post',
credentials: "same-origin",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: $.param(myparams0)
})
]).then(([aa, bb]) => {
$body.removeClass('loading');
console.log(aa);
return [aa.json(),bb.json()]
})
.then(function(responseText){
console.log(responseText[0]);
}).catch((err) => {
console.log(err);
});
我想要的只是能够访问data.qry1.我尝试使用 responseText[0].data.qry1 或 responseText[0]['data']['qry1'] 但它返回未定义.下面是 console.log responseText[0] 的输出.console.log(aa) 给出 Response {type: "basic" ...
All I want is to be able to access data.qry1. I tried with responseText[0].data.qry1 or responseText[0]['data']['qry1'] but it returned undefined. This below is the output from console.log responseText[0]. The console.log(aa) gives Response {type: "basic" ...
Promise {<resolved>: {…}}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
data: {qry1: Array(35)}
errors: []
推荐答案
显然 aa.json()
和 bb.json()
在解析之前返回,添加async/await
即可解决问题:
Aparently aa.json()
and bb.json()
are returned before being resolved, adding async/await
to that will solve the problem :
.then(async([aa, bb]) => {
const a = await aa.json();
const b = await bb.json();
return [a, b]
})
Promise.all([
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2')
]).then(async([aa, bb]) => {
const a = await aa.json();
const b = await bb.json();
return [a, b]
})
.then((responseText) => {
console.log(responseText);
}).catch((err) => {
console.log(err);
});
仍在寻找更好的解释
这篇关于如何返回 Promise.all 获取 api json 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何返回 Promise.all 获取 api json 数据?


基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01