struggle to wrap promise with async await - javascript

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))

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() in getUsers()? async/await suppose to eliminate then() 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);
})();

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();

you have the syntax wrong:
const getusers = async () => {
...
}
const is optional

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;
};

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

Related

I had 3 APIs need to called one after one

I create reactjs app when user ask for login I send three request
getToken();
createLogWithToken();
createRequestwithLog();
every function depend on the pervious one
here is my code
getToken = async (){
axios.post('getToken')
.then(response => {
this.setState({ token: response.data.token });
})
}
createLogWithToken = async (){
axios.post('createLogWithToken',{token:this.state.token})
.then(response => {
this.setState({ log_id: response.data.log_id });
})
}
createRequestwithLog = async (){
axios.post('createRequestwithLog',{token:this.state.token, log_id: this.state.log_id})
.then(response => {
this.setState({ request_id: response.data.request_id });
})
}
onPress = async () =>{
await this.getToken();
await this.createLogWithToken();
await this.createRequestwithLog();
}
I got error on the second commands as the required parameters is null
How can I call then and await till the the setstate done
Edit >>
I changed my code to be
getToken = async (){
await axios.post('getToken')
.then(response => {
this.setState({ token: response.data.token });
return (response.data.token);
})
}
createLogWithToken = async (token){
await axios.post('createLogWithToken',{token})
.then(response => {
this.setState({ log_id: response.data.log_id });
return response.data.log_id;
})
}
createRequestwithLog = async (token, log_id){
await axios.post('createRequestwithLog',{token, log_id})
.then(response => {
this.setState({ request_id: response.data.request_id });
return response.data.request_id;
})
}
onPress = async () =>{
let token = await this.getToken();
let log = await this.createLogWithToken(token);
let request = await this.createRequestwithLog(token,log);
}
but I still get error that token undefine
Several things:
The functions you are awaiting aren't "awaitable". You need to return a promise.
You can just await your axios calls directly like this const token = await axios.post...
setState isn't synchronous. You don't know if it's defined by the time you call the next endpoint. You should just set them in normal variables. If you also need them as state, you can do that too, but it doesn't look necessary
See How to structure nested Promises
fetch(url)
.then(function(response) {
return response.json()
})
.then(function(data) {
// do stuff with `data`, call second `fetch`
return fetch(data.anotherUrl)
})
.then(function(response) {
return response.json();
})
.then(function(data) {
// do stuff with `data`
})
.catch(function(error) {
console.log('Requestfailed', error)
});
getToken = async () {
const token = (await axios.post('getToken')).data.token;
this.setState({ token });
return token;
}
createLogWithToken = async (token) {
const logId = (await axios.post('createLogWithToken',{ token })).data.log_id;
this.setState({ log_id: logId });
return logId;
}
createRequestwithLog = async (token, logId) {
const requestId = (await axios.post('createRequestwithLog',{ token, log_id: logId })).data.request_id;
this.setState({ request_id: requestId});
}
onPress = async () => {
const token = await this.getToken();
const logId = await this.createLogWithToken(token);
this.createRequestwithLog(token, logId);
}

Issue with axios request

I am having issue with getting my axios request to work. I am following pattern shown me in one of the Udemy courses. Interesting thing is that I can console.log data, but I can't return data, and save it to a variable. Any help would be appreciated.
Have a nice day!
const get = async () => {
const res = await axios.get(
"https://www.themealdb.com/api/json/v1/1/list.php?i=list"
);
return res;
};
async means your function returns an promise. Thats a basic fact
const get = async () => {
const res = await axios.get(
"https://www.themealdb.com/api/json/v1/1/list.php?i=list"
);
return res;
};
get().then(result => {
console.log(result);
})
Read about it: https://javascript.info/async-await
However you do not need async in this case because axios is already returning an promise
const get = () => axios.get("https://www.themealdb.com/api/json/v1/1/list.php?i=list")
You should return res.data
import axios from 'axios';
const get = async () => {
const res = await axios.get(
"https://www.themealdb.com/api/json/v1/1/list.php?i=list"
);
return res.data;
};
const print = async()=>{
const resp = await get();
console.log(resp);
}
print();

Async Function returning Undefined when calling it

I'm Having some trouble with this function on a React project
let fetchData = async (event, imagen) => {
const apiURL = `https://some_api_call/${imagen}`;
await axios.get(apiURL).then((response) => {
console.log(response.data.Imagen1.data);
return response.data.Imagen1.data;
});
When i call it the Console.log returns Undefined but the console log above returns the data
fetchData(event, rowData.Codigo).then(function (response) {
console.log(response);
});
let fetchData = async (event, imagen) => {
const apiURL = `https://some_api_call/${imagen}`;
return await axios.get(apiURL);
}
fetchData(event, rowData.Codigo).then(function (response) {
console.log(response);
});
Your fetchData function has no return statement. You probably don't want to use then when there is await:
async function fetchData(event, imagen) {
const apiURL = `https://some_api_call/${imagen}`;
const response = await axios.get(apiURL)
console.log(response.data.Imagen1.data);
return response.data.Imagen1.data;
}

Return resolve-value from async function

In my project I use promise (code below), how it is possible, that promise still pending, when I used keyword await. Can someone help me figure out, what I'm doing wrong?
const getTs = async () => {
const response = await axios.get('...')
.then(res => res.data)
.catch(() => 'ERROR');
return response;
};
console.log(getTs()); // Promise { <pending> }
The await does only stop the execution of the async function body, nothing else. The caller is not blocked, the code is still asynchronous, and you get back a promise. If you want to log the result, you have to wait for it.
const getTs = () => axios.get('...').then(res => res.data).catch(() => 'ERROR');
getTs().then(console.log);
// ^^^^^
or
async function getTs() {
try {
const res = await axios.get('...');
return res.data;
} catch (e) {
return 'ERROR';
}
}
async function main() {
const response = await getTs();
// ^^^^^
console.log(response)
}
main();
getTs will be resolved once the request is resolved. So you have to await the response like :
const getTs = async () => {
const response = await axios.get('...')
.then(res => res.data)
.catch(() => 'ERROR');
return response;
};
getTs().then(response => console.log(response));

how to properly use the async and await keywords within a map

I have the following snippet of code
export const fetchPosts = () => async dispatch => {
const res = await axios.get(`${url}/posts`, { headers: { ...headers } });
console.log(res.data);
let posts = res.data.map(p => (p.comments = fetchComments(p.id)));
console.log(posts);
dispatch({ type: FETCH_POSTS, payload: res.data });
};
export const fetchComments = id => async dispatch => {
console.log(id)
const res = await axios.get(`${url}/posts/${id}/comments'`, {
headers: { ...headers }
});
console.log("id", id);
return res.data;
};
when i console log the posts, i get 2 functions returned. what is the proper way in which i should call the fetch comments for this function to return me the desired value?
Add this:
const postsResult = await Promise.all(posts)

Categories

Resources