Resolving a promise within a function [duplicate] - javascript

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

Related

how to access data outside promise .then [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 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?

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

Javascript - How to wait for a async function to finish to execute another function then? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm working on two functions about my project. First function is async function:
async function abc(params) {
(...)
var sdata = JSON.stringify(params);
fetch(...)
.then(response => response.json())
.then(data => {
/*do something*/
})
.catch(err => {
/*err do something*/
})
}
Second function is:
function xyz (param){
irrevelantFunction(param);
}
I tried to execute this two functions like below:
abc(params).then(xyz(param));
but it doesn't work. How can I solve this problem? Many thanks for your precious support.
If you are using async then you can avoid .then, kindly see the sample snippet code
async function abc(params) {
var sdata = JSON.stringify(params);
try{
const response = await fetch(...)
if(response.ok){
const body = await response.json();
xyz(body)
return
}
const cusotomError = {
message: 'something went wrong'
}
throw customError
}catch(error){
console.log(error) // you can show error to ui logic
}
function xyz (param){
irrevelantFunction(param);
}

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

Promise Pending while using map function [duplicate]

This question already has an answer here:
How to get a value from a "Promise" object
(1 answer)
Closed 4 years ago.
I'm trying to use the mongoose to try to fetch all the records under the Profile Schema using the find() method. The code looks fine to me and when I console.log the code block, it returns Promise { <pending> }.
I tried different approaches with no hope. Any help would be appreciated.
Thanks,
Here is my Code:
return Profile.find()
.then(profiles => {
return profiles.map(profile =>{
return {
...profile._doc
};
});
}).catch(err => {
//console.log(err);
throw err;
})
That would be because the promise is in pending state.If you need the data after the promise has been resolved you would have to add a then callback.
function getProfiles(){
return Profile.find()
.then(profiles => {
return profiles.map(profile =>{
return {
...profile._doc
};
});
}).catch(err => {
//console.log(err);
throw err;
})
}
getProfiles().then(profiles => console.log('profiles',profiles))

Categories