请问,如何将 fetch 的输出保存到变量中——以便能够像处理对象一样使用它?
这是代码:
var obj;
fetch("url", {
method: "POST",
body: JSON.stringify({
"filterParameters": {
"id": 12345678
}
}),
headers: {"content-type": "application/json"},
//credentials: 'include'
})
.then(res => res.json())
.then(console.log)
最后的 console.log
将显示一个对象。但是当我试图将它保存到变量 .then(res => obj = res.json())
而不是 console.log(obj)
将不会保存对象,而是 Promise。
请问,如何将它变成保存在变量中的对象?
原文由 Vlasta Po 发布,翻译遵循 CC BY-SA 4.0 许可协议
.json()
是一个async方法(它返回一个Promise本身),所以你必须在接下来分配解析值.then()
现代异步/等待等效
你必须
await
.json()
方法。