gpt4 book ai didi

javascript - 编辑 Promise 结果 (JavaScript)

转载 作者:行者123 更新时间:2023-11-30 19:31:31 25 4
gpt4 key购买 nike

我想编辑一个 res.json,回调(Promise.then)的结果是像这样的关联数组 "{category:"tennis",data:res.json()}"

然后我想得到一个没有 Promise 类型的 it

我试过了,但它返回了 Promise 类型

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

最佳答案

因为 fetch 返回一个 Promise,并且使用 .json()(或 .text() 等)使用 Promise 给你另一个 Promise,你需要调用两次.then;将另一个 .then 放入您的初始映射函数中,就像您对初始 const promise 所做的那样。您还应该避免 explicit promise construction antipattern :

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))

关于javascript - 编辑 Promise 结果 (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56388970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com