编辑承诺结果(JavaScript)
我想编辑一个res.json,回调(Promise.then)的结果是关联数组,如“{category:“netsines”,data:res.json()}” 然后我想得到一个没有承诺的类型 我试过了,但它返回了承诺类型编辑承诺结果(JavaScript),javascript,promise,Javascript,Promise,我想编辑一个res.json,回调(Promise.then)的结果是关联数组,如“{category:“netsines”,data:res.json()}” 然后我想得到一个没有承诺的类型 我试过了,但它返回了承诺类型 const promise = new Promise(function(resolve,reject) { fetch("http://localhost:100/api/v1/categories/map").then(response => resol
const promise = new Promise(function(resolve,reject) {
fetch("http://localhost:100/api/v1/categories/map").then(response
=> resolve(response.json()))
});
promise.then(value => Promise.all(value.category.map(
category => {
return (fetch("http://localhost:100/api/v1/categoriescategory=tennis"))
}
))
.then(responses => {console.log(responses);
return Promise.all(responses.map(res=> {
console.log(res.json()) <- this is not Promise
return(
{category:"tennis",data:res.json()} <- this is Promise
)
} )
)}))
.then(value=>console.log(value)) // {{category:"tennis",Promise{data:data}} <- i want to unwrap Promise
const promise=新承诺(函数(解析、拒绝){
取回(“http://localhost:100/api/v1/categories/map)然后(回应)
=>解析(response.json())
});
然后(value=>promise.all(value.category.map(
类别=>{
返回(获取)http://localhost:100/api/v1/categoriescategory=tennis"))
}
))
.then(responses=>{console.log(responses);
返回Promise.all(responses.map)(res=>{
console.log(res.json())因为fetch
返回一个承诺,并使用.json()
(或.text()
等)使用该承诺给您另一个承诺,您需要调用。然后
两次;在初始映射函数中放入另一个。然后
,就像您使用初始常量承诺一样。您还应该避免:
这是我的错误,所以我要编辑它!!你可以用const promise=fetch(“http://localhost:100/api/v1/categories/map)然后(response=>response.json()
因为fetch已经返回了一个promise,promises就是这样工作的除非每次调用categoriescategory=netsing
都返回不同的内容,否则它看起来像是在映射值。category
数组,但你没有使用它的任何值。category
变量没有使用。这是有意的吗?听起来像是这样就像您可能只会发出两个请求一样,不是一个请求后再请求类别中的每个项目
有人实际使用解析
作为解析
,而不是完成
:O
const promise = fetch("http://localhost:100/api/v1/categories/map").then(response => response.json());
promise.then(value => Promise.all(value.category.map(
category => {
return fetch("http://localhost:100/api/v1/categoriescategory=tennis")
.then(response => response.json());
// ^^^^^^^^^^^^^^^^^^^^^^^^^
}
))
.then(responseObjects => {
return Promise.all(responseObjects.map(responseObject => {
return {
category: "tennis",
data: responseObject
}
}))
}))
.then(value => console.log(value))