How to use results from asynchronous function in Angular - javascript

I'm trying to use the results from my asynchronous function inside another function, but it keeps saying the result is undefined.
This is my structure of my calling function:
async callingFn() {
let value = await calledFn();
console.log(value);
}
This is the structure of the function I'm calling:
calledFn() {
this.myService.getHttpResponse().subscribe(
(resp: any) => {
var values = JSON.parse(resp);
console.log(values);
return values;
},
error => {
console.error(error);
}
);
}
When I log values in calledFn, the result is as expected. However, when I log the return value of calledFn in callingFn, it returns undefined.
What am I doing wrong?

You are not returning from the calledFn. The subscription method is returning though.return the http service call
calledFn() {
return this.myService.getHttpResponse().subscribe(
(resp: any) => {
var values = JSON.parse(resp);
console.log(values);
return values;
},
error => {
console.error(error);
}
);
}

Related

Get value returned from Promise in JavaScript

I´m new to JavaScript and a little bit confused about Promises, this is what I have:
export const testFunction = () => dispatch => {
otherFunction().then(( response ) => {
//do something...
return response;
}).catch(( error ) => {
//do something...
return error;
});
}
In another file I'm trying to get the value returned from the then like this:
let result = this.props.testFunction()
And like this:
let result = this.props.testFunction ().then(( result ) => {
console.log(result);
}).catch(( error ) => {
console.log(result); // undefined
});
But I get undefined as the result, what is the correct way of getting that value?
testFunction is not returning a Promise so you can't use then or catch and returns undefined because well, it's not returning any thing.
Try to return a promise like the example below however I am not sure what the dispatch argument supposed to do so I have removed it and hopefully this'll help:
export const testFunction = () => {
return new Promise((resolve, reject) => {
otherFunction().then(( response ) => {
//do something...
resolve(response);
}).catch(( error ) => {
//do something...
reject(error);
});
});
}
when you are trying to return a promise to use it in another file, you must use the following syntax:
const testFunction = () => {
return new Promise((resolve, reject) => {
if (error) {
return reject(error); // this is the value sent to .catch(error)
}
return resolve(valueToReturn); // this is the value sent to .then(result)
});
}
This is how you create a promise to use where you want, if it has an error it will sent to catch block, otherwise you should see the console.log(result) value.
And in your external file you can use the syntax that you are using, try it in that way to see the console.log value.
Here is a link to see more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

declare promise type in typescript of a function

I saw this code somewhere, just curious, why need to specify Promise in the return type? isn't the function return data which is an object? and what's the | null for?
const getSomething = async (
id: string
): Promise<UserData | null> => {
try {
const { data } = await axios.get(
`${API}/user?id=${id}`
);
return data;
} catch (err) {
if (err.response) {
return err.response.data;
}
return null;
}
};
Async functions always return Promises - that way, the asynchronous awaits can be waited for inside the function, and the result can be used outside the function.
Here, the getSomething tries to retrieve data from an axios call. If the call succeeds, the data is just returned:
return data;
But if the call doesn't succeed, it'll return one of the following instead:
if (err.response) {
return err.response.data;
}
return null;
If the axios call throws, and there is no err.response property, then null will be returned. If you left out the | null, the getSomething function wouldn't be typed properly.

Returning Observable from function

I have the following function in typescript:
getConfigurations() {
let sessionConfig = sessionStorage.getItem('config');
if(config)
return of(sessionConfig);
else {
this.dataService.getRoute('configurations').subscribe(
route => this.http.get<any[]>(route.ToString()).subscribe(
result => {
sessionStorage.setItem('config', result);
return of(result);
},
error => {
alert(error);
}),
error => {
alert(error);
}
);
}
}
The function should return a string if the sessionStorage key is already existent or use dataService to retrieve the value from back end and then set the value in the session. I'd like to return the value set in sessionStorage too (result), but I couldn't find a way to do it.
The function getRoute from dataService is:
getRoute(service: string){
return this.http.get('urlToMyBackendWebApi');
}
Where http is the Angular HttpClient.
How could I get the value returned from getConfigurations() ?
I tried to subscribe to getConfigurations. I have no problems with the if condition (the string sessionConfig is returned) but how to get the result from the else condition? Should I return an observable of the entire part? In this case, how could I read the return?
Don't subscribe to the observable, return it, and use the tap operator to store the response:
getConfigurations() {
let sessionConfig = sessionStorage.getItem('config');
if(config)
return of(sessionConfig);
else {
return this.dataService.getRoute('configurations').pipe(
mergeMap(route => this.http.get<any[]>(route.ToString()),
tap(result => sessionStorage.setItem('config', result))
);
}
}

Return a data out of a promise and get it in another method

I'm missing something on how to use async/await and probably promises methods too.
Here is what I am trying to do:
login-form-component.html
<button (click)="sinInWithFacebook()">Sign In with Facebook</button>
login-form-component.ts
async sinInWithFacebook() {
const loginResponse = await this.auth.signInWithFacebook();
console.log(loginResponse); // it returns undefinied
}
auth.service
signInWithFacebook() {
try {
this.fb.login(['email'])
.then((loginResponse: FacebookLoginResponse) => {
const credential = firebase.auth.FacebookAuthProvider.credential(loginResponse.authResponse.accessToken);
return <LoginResponse>{
result: this.auth.auth.signInWithCredential(credential)
}
})
}
catch (e) {
return {
error: e
}
}
}
loginResponse will always returns undefinied when I want it to return the result object. I believe it has something to do with asynchronous methods. Can you help me out?
Thanks
You should return the result from signInWithFacebook function:
try {
return this.fb.login(['email'])
.then((loginResponse: FacebookLoginResponse) => {
const credential = firebase.auth.FacebookAuthProvider.credential(loginResponse.authResponse.accessToken);
return <LoginResponse>{
result: this.auth.auth.signInWithCredential(credential)
}
})
}
your function doesn't return anything. And the try .. catch block doesn't work that way for Promises.
signInWithFacebook():Promise<LoginResponse> {
return this.fb.login(['email'])
.then((loginResponse: FacebookLoginResponse) => {
const credential = firebase.auth.FacebookAuthProvider.credential(loginResponse.authResponse.accessToken);
//my guts tell me that `this.auth.auth.signInWithCredential` is async as well.
//so let the promise chain deal with that/resolve that
return this.auth.auth.signInWithCredential(credential);
})
.then(
result => ({ result }),
error => ({ error })
);
}

react native how to get return from a promise

my problem is i want to get a json from this function but all i get is a only a promise and why i choose this way because in app that i'm working on it works dynamicly but the only place that i see i can put this promise is render()
this is my code :
var userInfo = (async()=>{
var value = await AsyncStorage.getItem("#user_info");
value = JSON.parse(value);
return value ;
})();
and this is my result :
Promise {
"_40": 0,
"_55": null,
"_65": 0,
"_72": null,
}
but what i want to get is a json what sould i have to do ?
You have to call this function from componentDidMount and after the promise completes, call setState.
Here is a canonical example of how to do this:
class User extends React.Component {
state = { user: null };
render() {
return this.state.user && <div>{this.state.user.name}</div>;
}
async componentDidMount() {
const value = await AsyncStorage.getItem("#user_info");
if (!this._unmounted) {
const user = JSON.parse(value);
this.setState({ user: user });
}
}
componentWillUnmount() {
this._unmounted = true;
}
}
You should return value.json() . Try this
var userInfo = (async()=>{
var value = await AsyncStorage.getItem("#user_info");
return value.json() ;
})();
In addition, AsyncStorage.getItem is an asynchronous function, you will need to wrap that in try and catch in case if any error happened during the process
Note: If you use an await inside a function that is not explicitly declared with async, you'll end up with an Unexpected token syntax error.
async userInfo(){
try{
var value = await AsyncStorage.getItem("#user_info");
return value.json() ;
}
catch(e){
console.log('caught error', e);
// Handle exceptions
}
}
I think it is because your function is self-executing.
You should be able to access the value if you remove the self-execution
var userInfo = async () => {
var value = await AsyncStorage.getItem("#user_info");
value = JSON.parse(value);
return value ;
});
As AsyncStore.getItem is a Promise you could also use .then method
const userInfo = () => {
AsyncStorage.getItem("#user_info").then((response) => {
console.log(response);
});
}

Categories