Example using a Promise
var getPosts = () => {
fetch('/wp-json/wp/v2/posts')
.then((response) => response.json())
.then((json) => { console.log(json); });
};
Example using async / await
Note: await
only works when inside an async
function.
var getPosts = async () => {
var response = await fetch('/wp-json/wp/v2/posts');
var json = await response.json()
console.log(json);
};
Equivalent Functions
These two functions are equivalent.
async function exampleAsync() {
return 'Tada';
}
function examplePromise() {
return new Promise((resolve) => resolve('Tada'));
}
Both can be called (from within an async
function) using the await
keyword.
async function runMe() {
console.log(await exampleAsync());
console.log(await examplePromise());
};
runMe();
Or both can be called with a .then()
method on the response.
exampleAsync().then(value => console.log(value));
examplePromise().then(value => console.log(value));
Leave a Reply