This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I am using axios to retrieve data from my BackEnd but the promise is still pending.
I have used .then() even async and await. I am using .then(res => res.data) since i know that every promise has "data" key holding the retrieved data and that after that it will be returned this way. I also binded the function in the constructor!
async getTrackInfo() {
return await axios.get('http://localhost:60231/api/values')
.then(res => res.data);
};
componentDidMount() {
const data = this.getTrackInfo();
console.log(data);
this.setState({
tracks: data
});
}
But unfortunately, it returns undefined.
Following code would work:-
async getTrackInfo() {
return await axios.get('http://localhost:60231/api/values')
.then(res => res.data);
};
async componentDidMount() { // Make this function async
const data = await this.getTrackInfo(); // add await here
console.log(data);
this.setState({
tracks: data
});
}
Related
This question already has answers here:
async/await implicitly returns promise?
(5 answers)
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
Async function returning promise, instead of value
(3 answers)
How can I access the value of a promise?
(14 answers)
What are asynchronous functions in JavaScript? What is "async" and "await" in JavaScript?
(2 answers)
Closed 19 days ago.
I am trying to fetch data from an endpoint in my project, but continue to get a Promise back instead of the actual data. First of all I should say that I am not getting an error, however I just don't understand why I couldn't handle the returned data from the api call outside of the function.
So I have this function fetchUser that makes a call to the API, and returned the data successfully when I log it to the console. But what I want is to be able to use this data in my JSX. Below is the function call to the API route:
const fetchUser = async () => {
const baseUrl = "/api/user";
const response = await axios.get(baseUrl);
const { data } = response;
const role = data.map((item) => {
const { role } = item;
return role;
});
return role;
};
const userRole = fetchUser().then((result) => {
console.log(result) // returned the data as I expected and wanted (e.g: [Brand])
return result;
});
console.log("Role", userRole); // Returned a 'Promise'(as shown below)
Role:
Promise {<pending>}
[[Prototype]]
Promise
[[PromiseState]]
"fulfilled"
[[PromiseResult]]
Array(1)
Please point me in the right direction to resolve this issue
This happens because of the async nature of the Promise object. What you're storing in the userRole variable is a Promise object.
One way to work this out is either await the response, like this:
// This is my preferable method, as I can avoid nested calls
try {
const userRole = await fetchUser();
console.log(userRole)
}
catch (error) {
console.log(error)
}
The other way is to handle your data inside the .then(), like this:
fetchUser()
.then(res => console.log(res))
.catch(error => console.log(error))
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I build a login function and check the credentials on my backend-server. I have to wait for the response of the server. I have used an official guide to es7-async-await.js, but it does not work. I have tried everything that async/await and promises give, but it does not work at all. I read all the posts regarding this issue. What am I doing wrong?
My function:
async getCredentials(pUser, pCipher) {
var url = new URL(serviceURL);
var params = {
user: pUser,
p: pCipher
}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
// await response of fetch call
let response = await fetch(url, {
method: 'get',
headers: { }
});
// only proceed once promise is resolved
let data = await response.json();
// only proceed once second promise is resolved
return data;
},
my function call:
this.getCredentials(this.input.username, cipher)
.then(data => this.checkResponse = data.items)
.catch(reason => console.log(reason.message))
console.log("data: ->>>> " ,this.checkResponse);
the result:
data is always empty because the function does not wait
can you put the console.log in the .then?. Is printing something?. If you do a console.log when the data is not received will not print anything.
this.getCredentials(this.input.username, cipher)
.then(data =>
{
this.checkResponse = data.items
console.log("data: ->>>> " ,this.checkResponse);
})
.catch(reason => console.log(reason.message))
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I know its may be dumb question, I've already read similar questions. Tryed to do this but it not work at all in my code. I got function
const request = async (url) => {
const response = await fetch(url);
const result = await response.json();
return result;
}
it return another promise
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(100)
I need "array" NOT "promise". Tried to use Promise.resolve() but looks like I have no idea how to use it here.. all my attempts not work. always get error "resolve is not defined". Please just help if you know how to do it.
Here is a working example of how this might work end to end:
const request = async (url) => {
const response = await fetch(url);
return response.json(); // no need to await the parsing of json
}
// now we call the function, I'm using a self-invoking function here but I assume you will run this code in your own function. Just make sure it's also an `async` function.
(async () => {
const yourData = await request('https://bronzies.com/api/version');
// we have to await the async function to resolve before we can see the data
console.log(yourData);
})();
Another way to get the data out is to use then instead of async/await
request('https://bronzies.com/api/version')
.then( yourData => console.log(yourData))
.catch( error => console.error(error));
Hope this helps
You don't need to call await again. The first await does resolve the promise, and then response.json() parses the json and returns it as resolved
const request = async (url) => {
const response = await fetch(url);
return response.json();
}
Calling the above function:
const results = await request(url)
console.log(results)
OR
request(url).then(results => console.log(results))
This question already has answers here:
How do I access previous promise results in a .then() chain?
(17 answers)
Closed 3 years ago.
I have a chain of promises in my backend and i need to access the result of the first promise in the second one
mongo.connect()
.then((client) => {
return circolari.infiniteScroll(client, currCirc)
})
.then(({ data, client }) => {
mongo.close(client)
res.send(data)
})
.catch(error => res.sendStatus(error.message))
I need to access client to close the connection in the second promise.
Right now to achieve that I resolve in circolari.infiniteScroll(client, currCirc) an object like this:
resolve({
data: data,
client: client
})
With this workaround it works, but I think there's a better way to do it, thank you.
You can make it a little bit shorter:
mongo.connect()
.then(client => circolari.infiniteScroll(client, currCirc)))
.then(({ data, client }) => {
mongo.close(client);
res.send(data);
})
Or using await and async:
async function returnResponse(res) {
let client;
try {
client = await mongo.connect();
const data = await circolari.infiniteScroll(client, currCirc);
res.send(data);
} catch (err){
res.sendStatus(err.message)
} finally {
await mongo.close(client); // close connection in every case
}
}
foo();
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am trying to understand why promise is not resolved when I am using async and await keywords. Below is the code that I have
var a = 'https://jsonplaceholder.typicode.com/posts';
async function fetchData() {
const response = await fetch(a);
const data = await response.json();
return data;
}
console.log(fetchData());
fetchData function should return actual datas but it always returns a promise object. What am I doing wrong?
I am expect the following output [{userId: 1, name: 'ss'}]after invoking fetchData()
The way async works is that it returns a promise. So what you can do is:
fetchData().then(data => console.log({data}))
And you'll print out your data!
Also, you don't need that line:
const data = await response.json();
because the .json() method is synchronous, and thus there's no need to wait for a promise to be resolved.
So a simpler way to do it would be:
var a = 'https://jsonplaceholder.typicode.com/posts';
async function fetchData() {
const response = await fetch(a);
data = response.json();
// do stuff with data, synchronously
return data;
}
so you want to write code without callbacks, but then what you need is to use fetchData() in an async context, so here's how you can do that:
async function asyncPrint(aPromise) {
console.log(await aPromise);
}
asyncPrint(fetchData);
and if you're evil, you could do:
console.asyncLog = asyncPrint;
so you can run:
console.asyncLog(fetchData());