在这里与promise 搏斗...
我的用户发出需要在后端进行多个REST调用的单个请求.我将用户发出的每个请求和两个REST响应作为一个项存储在‘Records’数组中,如下所示:
[
{
call:userRequest,
responses: [
{
source:source1
response:responseText
},
{
source:source2
response:responseText
}
]
}
]
我使用map函数进行多个REST API调用.我使用‘setThisCall’方法处理每个响应,该方法将每个响应的详细信息添加到数组‘thisCall’.完成后,将‘thisCall’用作‘Records’数组中‘Responses’的值,该值被分配给‘thisCall’.
await Promise.all(urls.map(async url => {
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: messageBody
})
.then((response) => response.json())
.then((data) => {
setThisCall(prev => ([ //sets thisCall
...prev,
{
source: source,
response: data.body
}
]))
})
})).then(()=>{
console.log("now adding to records")
setRecords(prev => ([ //sets records
{
call: requestText,
reponses: thisCall
},
...prev
]))
})
我try 使用Promise.all()让map函数完成垃圾处理,处理响应,并使用‘THEN’将调用添加到下一个‘Record’项.
但最终的‘THEN’是在生成‘thisCall’之前触发的,从而导致‘Records’中的‘Response’值为空.
我如何让‘setRecords’在其余代码完成后发生?