how to access data outside promise .then [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How can I access the value of a promise?
(14 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed last year.
so I have class for data object, I'm trying to define one property where I fetch it's value from api
this is how the class looks like:
export default class User extends Base {
....
constructor(packet: Packet) {
....
this.card = this.get_user_card() // showing undefined
}
get_user_card(): Card {
this.rest.api(...).get().then((res: any) => {
console.log(res.data); // return the card data
return res.data;
})
}
}
it's showing undefined when I set to card properties outside the function
I even tried this but this one showing Promise <pending> I can't use await inside constructor
return this.rest.api(...).get().then((res: any) => {
return res.data;
})
and this but it's showing undefined for both and if I make it asynchronous it will return promise pending for the this.card
const res = this.rest.api(...).get()
console.log(res.data) //undefined
return res.data; //undefined too
tried this one too and doesn't work
this.rest.api(...).get().then((res: any) => {
this.channel = res.data; //not working
// even assign
Object.assign(this, { card: res.data }); //not either
})
but console logging inside their .then is working. can someone help me or have other solution?

Related

axios data is undefined [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 months ago.
I'm trying to perform an axios get request.
axios
.get("http://10.10.0.145/api/session", {
headers: {
'Cookie' : user_cookie
}
},
)
.then(res => {
result = res.data;
id_user_intervention = res.data.id;
console.log(id_user_intervention); //IS NOT UNDEFINED
})
.catch(error => {
console.error(error)
})
console.log(id_user_intervention); //IS UNDEFINED
I need to use id_user_intervention outside the axios request. I assign res.data.id to id_user_intervention, but this variable is undefined outside the axios request...how can I solve this problem?
First of all, it's better you learn async/await on javascript. Then, try the following solution:-
const testFunction = async () => {
let id_user_intervention = null;
try {
const response = await axios.get("http://10.10.0.145/api/session", {
headers: {
'Cookie': user_cookie
}
})
id_user_intervention = response.data.id;
} catch (err) {
console.error(err);
}
return id_user_intervention;
}
const anotherFunction = async () => {
const data = await testFunction();
console.log(data);
}
Hope it will work properly.

Return value from fetch and return again [duplicate]

This question already has answers here:
How can I access the value of a promise?
(14 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I'm making a API call/fetch(), to check a user's logged in status and I need to return true or false from the fetch. (Don't ask why, I just need to do this specifically for a project at work, so must be done this way).
I have some code below:
which returns a fetch
And returns the response successfully, outside the main function checkLoggedInStatus().
However, if the logged in status === NotloggedIn, I want to return true.
In this example below, my code returns NotloggedIn. But does not return true.
How can I do this?
Thanks,
function checkLoggedInStatus() {
let data;
return fetch("www.MYAPI.com")
.then((response) => response.text())
.then((result) => {
data = JSON.parse(result);
return data;
})
.catch((error) => console.log("error", error));
};
checkLoggedInStatus().then(data => {
console.log("data.Status", data);
if (data === "NotLoggedIn") {
return true;
} else {
return false
};
})

Resolving a promise within a function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am having trouble resolving this promise.
const getAge = (actorId) => {
return (
axios.get(`https://api.themoviedb.org/3/person/${actorId}?api_key=${process.env.REACT_APP_API_KEY}&language=en-US`)
.then(function (response) {
return moment().diff(response.data.birthday, 'years')
})
.catch(function (error) {
console.log(error);
})
)
}
console.log(getAge('5000'), 'FUNCTION')
It doesnt ever resolve the promise and returns pending
I have tried a number of different ideas and none seem to work. What Am I missing?
Thanks
You need to call .then to get the value or wrap the call within a async function. For example:
getAge('5000')
.then(val => console.log(val, 'FUNCTION'));
Alternatively, wrapping with async:
(async () => {
const val = await getAge('5000');
console.log(val, 'FUNCTION');
})();

Async function returning pending promise, despite use of await [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
async/await implicitly returns promise?
(5 answers)
Closed 3 years ago.
In the below code snippet I am trying to understand why the function does not return the result of the promise.
It first logs Promise { <pending> }, then logs the response variable with the correct data from the AWS API describing the table.
Why is it doing this? I've tried wrapping the function in another async function and awaiting it and I get the same result.
const AWS = require('aws-sdk');
AWS.config.update({region: 'eu-west-2'});
const docClient = new AWS.DynamoDB;
async function describeTable() {
const params = {
TableName: 'weatherstation_test',
};
let response;
try {
response = await docClient.describeTable(params).promise();
console.log(response); // This logs second. It logs the data correctly
} catch (e) {
console.error(e)
throw e;
}
return response;
}
console.log(describeTable()); // This logs first. It logs Promise { <pending> }
Update
This still returns Promise { <pending> } even if I add .then(result => result).

How do I return the value of the promise, instead of returning the promise itself? (React/Redux) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am having an issue within one of my reducers where I have all of the information readily available to return to the front-end except for one array called "items" which I need to do an additional fetch to get more data back. The issue I am having with this fetch is that it ultimate leads to a return of a promise instead of returning the value. My question is how can I get the value instead of the promise? (e.g. via blocking everything else until the promise resolves and then sending that back).
I have commented throughout the below code to hopefully explain everything more clearly:
export const getItemsForHistory = createSelector(
[getAllHistory, getAllItems, getHistoryPage], (history, items, page) => {
let itemIds = `[a bunch of ids]`;
//this is the call I am making to fetch the additional data for "items"
//this return statement is sending back a promise and not a value
return getUpdatedItems(itemIds, items).then(result => {
//result is the actual value I want
return result;
}, error => {
//if the fetch fails, I would like to send a default value for "items"
//note, if I place this return outside of this entire promise and remove the promise, it works as expected with the default data
return history.map(h => items.get(h.get('item'), null))
}).catch(error => {
return history.map(h => items.get(h.get('item'), null))
})
}
)
//I would like for this method to run asychronously
const getUpdatedItems = async (itemIds, items) => {
let result = await fetchHistoryItemsDetail(itemIds);
return result;
}
const fetchHistoryItemsDetail = (itemIds) => {
let headers = {
"Content-Type": "application/json",
},
fetchUrl = `XXXXXXXXX`;
return fetch(fetchUrl, {
method: "POST",
headers: headers,
body: itemIds,
withCredentials: true,
crossDomain: true,
})
.then(response => {
return response.json();
})
.catch(error => {
throw error;
})
}
export const getSortedHistory = createSelector(
[getAllHistory, getItemsForHistory, getHistorySort, getHistoryPage], (history, items, sort, page) => {
//this is where items is ultimately retured to the front end but it is now a promise and not an array of data
//(from getItemsForHistory)
return sortedEntities(history, items, sort)
}
)
I hope that my question is clear, but please let me know if further elaboration is needed.
You cannot return data from within a promise's cats/error handler
If for both you want to send data, I would suggest wrapping in another promise that will always resolve
return new Promise((res) => {
//this is the call I am making to fetch the additional data for "items"
//this return statement is sending back a promise and not a value
getUpdatedItems(itemIds, items).then(result => {
//result is the actual value I want
res(result);
}, error => {
//if the fetch fails, I would like to send a default value for "items"
//note, if I place this return outside of this entire promise and remove the promise, it works as expected with the default data
res(history.map(h => items.get(h.get('item'), null)));
}).catch(error => {
res(history.map(h => items.get(h.get('item'), null)));
})
});

Categories