You need to await
all the things:
var UserInfo = (async function getUserInfo() {
var response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
// ``.json` also returns a promise, so use `await` to reference the actual result
const data = await response.json()
console.table(data)
// Since this variable comes from a function expression, explicitly return
// `response.json()` to set the final value as intended
return data
})();
item.setValue(await UserInfo);
If the main execution context (with item.setValue
) isn't inside an async
function,
you will have to wrap it with an async IIFE in order to use await
to set item.value()
.
The await keyword is only valid inside async functions. If you use it outside of an async function's body, you will get a SyntaxError.
Source: MDN
(async () => {
var UserInfo = await (async function getUserInfo() {
var response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
// ``.json` also returns a promise, so use `await` to reference the actual result
const data = await response.json()
console.table(data)
// Since this variable comes from a function expression, explicitly return
// `response.json()` to set the final value as intended
return data
})();
item.setValue(UserInfo);
})();
Here's another way, if you need to avoid using an async
wrapper in the upper scope:
// Simplify this method, not an IIFE any more
async function getUserInfo() {
var response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
const data = await response.json()
console.table(data)
return data
};
// This part doesn't need to exist inside an async function
getUserInfo()
.then((info) => item.setValue(info))
.catch((err) => console.error(err))