Reputation: 517
I got unexpected identifier but not sure what is the mistake. I'm using fetch which is already a promise.
async getUsers = () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
return resp
}
getUsers().then(users => console.log(users))
Upvotes: 1
Views: 1340
Reputation: 5698
const getUsers = async () => {
try {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1');
return resp.json();
} catch(e) {
console.error(e)
}
}
(async () => {
const users = await getUsers();
console.log(users)
})()
Use this, and run
Upvotes: 0
Reputation: 7742
Aside from the typo in the async word pointed by @acdcjunior, you're mixing async / await
with the usual promise handling (.then()
) which is not wrong but kind of defeats the point. Using only async / await
would look like:
const getUsers = async () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1');
return resp.json();
}
async function fetchUsers() {
try {
const users = await getUsers();
console.log(users);
} catch(err) {
console.log(err);
}
}
fetchUsers();
Upvotes: 1
Reputation: 135862
Notice the position of the async
keyword:
Not:
async getUsers = () => {
But:
getUsers = async () => {
Run:
getUsers = async () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
return resp;
};
getUsers().then(users => console.log(users))
As per comments:
Should I chain
then()
ingetUsers()
?async
/await
suppose to eliminatethen()
am I right?
Yes, you can await
any Promise
. Or use both .then()
sometimes and await
at others (like does the code above). But you could just use async
/await
as well.
The example below uses no .then()
:
getUsers = async () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1')
return resp.json();
};
(async () => {
// notice to use the await keyword, the code must be wrapped in an async function
const users = await getUsers();
console.log(users);
})();
Upvotes: 3
Reputation: 4464
Your syntax of declaring your function is wrong, here's some explanation.
If getUsers
is a method of a react component class the syntax should be :
getUsers = async () => {
const resp = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
).then(response => response.json());
return resp;
};
or :
async getUsers() {
const resp = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
).then(response => response.json());
return resp;
};
If it's outside of a react component class or in a stateless arrow function component you can use this syntax :
const getUsers = async () => {
const resp = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
).then(response => response.json());
return resp;
};
Upvotes: 0
Reputation: 4812
you have the syntax wrong:
const getusers = async () => {
...
}
const
is optional
Upvotes: 0