For example here is the content of a JSON on a remote URL:
{ "title": "The title", "description": "The description" }
Could you please help with this:
The function below displays "[object Promise]" in my DIV.
async buildWidget() {
var id = "whatever"
let data = await fetch('getItem.php?id=' + id + '&callback=getJSONP');
var json = data.json();
return json.title;
}
No JQuery please.
Thanks
Use await on .json() as it is asynchronous I.e.
async buildWidget() {
var id = "whatever"
let data = await fetch('getItem.php?id=' + id + '&callback=getJSONP');
var json = await data.json();
return json.title;
}
First of all .json() returns an promise and then also needs to await for it.
Second: async functions are asynchronouse they return an promise.
async buildWidget() {
var id = "whatever"
let data = await fetch('getItem.php?id=' + id + '&callback=getJSONP');
var json = await data.json();
return json.title;
}
buildWidget().then(title => {
console.log(title)
})
fetch method returns a promise, so just await and get the JSON response from it. You can then simply get the properties like data.title or data.description and render then to the DOM.
async function buildWidget() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
document.getElementById('data').innerHTML = data.title;
}
buildWidget();
<div id="data"></div>