问题
Please, how can I save output of fetch to a variable - to be able to work with it as with an object?
Here is the code:
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)
The final console.log will show an object. But when I tried to save it to variable .then(res => obj = res.json()) than the console.log(obj) will not hold the Object, but the Promise.
Any idea please, how to turn it into an Object saved in the variable?
回答1:
.json() is an async method (it returns a Promise itself), so you have to assign the parsed value in the next .then()
var obj;
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(data => obj = data)
.then(() => console.log(obj))
来源:https://stackoverflow.com/questions/45018338/javascript-fetch-api-how-to-save-output-to-variable-as-an-object-not-the-prom