I have an async function that fetch data. In order to manipulate the data returned, I used from() to convert the Promise to an observable and use pipe() to manipulate the data. Is is possible to convert it back to Promise after pipe()? I have tried the following but it didn't work:
getOrder() {
return from(asyncFunctionToGetOrder())
.pipe(map(data) =>
//Processing data here
return data;
))
.toPromise(); //This won't work
}
I don't know why you want to return promise, why cannot you convert to promise while fetching data, see this:
this.getOrder()
.toPromise()
.then((response:any) => {
this.records = response;
}).catch(error => {
console.log(error)
}).finally(() => {
// code to cleanup
});
Without Observable:
getOrder() {
return asyncFunctionToGetOrder().then(
(data) => {
// Processing data here
return Promise.resolve(data);
}
);
}
It should be working, though.
Remember that toPromise only return when the observable completes.
Also that if your promise rejects, you need to catch error.
Put together an example for you: https://stackblitz.com/edit/rxjs-4n3y41
import { of, from } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
const fetchCall = () => {
return Promise.resolve({a: 1, b: 2});
}
const problematicCall = () => {
return Promise.reject('ERROR')
}
const transformedPromise = from(fetchCall())
.pipe(map(data => data.a))
.toPromise()
const problematicTransformed = from(problematicCall())
.pipe(catchError(data => of(data)))
.toPromise()
transformedPromise.then((a) => console.log('Good boy', a));
problematicTransformed.then((a) => console.log('Bad boy', a));
Related
I have a service to get a list from server. But in this list I need to call another service to return the logo img, the service return ok, but my list remains empty. What i'm did wrong ?
I tried to use async/await in both services
I tried to use a separate function to get the logos later, but my html don't change.
async getOpportunitiesByPage(_searchQueryAdvanced: any = 'active:true') {
this.listaOportunidades = await this._opportunities
.listaOportunidades(this.pageSize, this.currentPage, _searchQueryAdvanced)
.toPromise()
.then(result => {
this.totalSize = result['totalElements'];
return result['content'].map(async (opportunities: any) => {
opportunities.logoDesktopUrl = await this.getBrand(opportunities['brandsUuid']);
console.log(opportunities.logoDesktopUrl);
return { opportunities };
});
});
this.getTasks(this.totalSize);
}
No errors, just my html don't change.
in my
console.log(opportunities.logoDesktopUrl);
return undefined
but in the end return filled.
info:
Angular 7
server amazon aws.
await is used to wait for promise.
You should return promise from getBrand if you want to wait for it in getOpportunitiesByPage.
Change the getBrand function as following.
getBrand(brandsUuid): Observable<string> {
this.brandService.getById(brandsUuid).pipe(map(res => {
console.log(res.logoDesktopUrl); return res.logoDesktopUrl;
}))
}
Change opportunities.logoDesktopUrl = await this.getBrand(opportunities['brandsUuid']); to opportunities.logoDesktopUrl = await this.getBrand(opportunities['brandsUuid']).toPromise();
Please make sure you imported map from rxjs/operators.
At first,when you await, you should not use then.
At second, async/await runs only with Promises.
async getOpportunitiesByPage(_searchQueryAdvanced: any = 'active:true') {
const result = await this._opportunities
.listaOportunidades(this.pageSize, this.currentPage, _searchQueryAdvanced)
.toPromise();
this.totalSize = result['totalElements'];
this.listaOportunidades = result['content'].map(async (opportunities: any) => {
opportunities.logoDesktopUrl = await this.getBrand(opportunities['brandsUuid']);
console.log(opportunities.logoDesktopUrl);
return opportunities;
});
this.getTasks(this.totalSize);
}
getBrand(brandsUuid) {
return new Promise((resolve, reject) => {
this.brandService.getById(brandsUuid).subscribe(res => {
console.log(res.logoDesktopUrl);
return resolve(res.logoDesktopUrl);
}, err => {
return reject(err);
});
});
}
But, because rxjs is a used in Angular, you should use it instead of async/await :
getOpportunitiesByPage: void(_searchQueryAdanced: any = 'active:true') {
this._opportunities.listaOportunidades(this.pageSize, this.currentPage, _searchQueryAdvanced).pipe(
tap(result => {
// we do that here because the original result will be "lost" after the next 'flatMap' operation
this.totalSize = result['totalElements'];
}),
// first, we create an array of observables then flatten it with flatMap
flatMap(result => result['content'].map(opportunities => this.getBrand(opportunities['brandsUuid']).pipe(
// merge logoDesktopUrl into opportunities object
map(logoDesktopUrl => ({...opportunities, ...{logoDesktopUrl}}))
)
),
// then we make each observable of flattened array complete
mergeAll(),
// then we wait for each observable to complete and push each result in an array
toArray()
).subscribe(
opportunitiesWithLogoUrl => {
this.listaOportunidades = opportunitiesWithLogoUrl;
this.getTasks(this.totalSize);
}, err => console.log(err)
);
}
getBrand(brandsUuid): Observable<string> {
return this.brandService.getById(brandsUuid).pipe(
map(res => res.logoDesktopUrl)
);
}
Here is a working example on stackblittz
There might be a simpler way to do it but it runs :-)
I have a main thunk that gets executed when clicking a button. Inside this thunk I want to call another thunk and wait for it to complete before moving forward. The second thunk executes a promise with nested promises. However, I haven't been able to figure out how to wait for the second thunk to complete its asynchronous operations.
I have tried using the return keyword on my thunk to make the call synchronous. I can't use the async keywords since I need this to work in IE 11.
I have also tried to make my second thunk return a promise and then do something like this dispatch(secondThunk()).then(...) but then it says that my thunk doesn't actually return a promise.
Here is some of my code:
export function mainThunk(): ThunkAction<void, void, void, AnyAction> {
return (dispatch: Dispatch<any>) => {
...do some stuff
dispatch(secondThunk());
...do other stuff
};
}
export function secondThunk(): ThunkAction<void, void, void, AnyAction> {
return (dispatch: Dispatch<any>) => {
return new Promise((resolve: any, reject: any) => {
someAsyncFunction()
.then((response) => {
return Promise.all(someArray.map(someId => {
return someOtherAsyncFunction(someId):
}));
})
.then((responses) => {
response.foreach(response => {
dispatch(someReduxAction(response.someField));
});
})
.then(() => {
resolve();
});
});
};
}
When I run my code the mainThunk is not waiting for the secondThunk to complete before executing. Can you help me figure out how to make this work?
You're almost there. In your mainThunk function you need to wait for the promise to resolve or reject. I've written my demo in Javascript and not Typescript. However the principles are the same. Code-sandbox here
import axios from "axios";
function mainThunk() {
secondThunk()
.then(data => {
console.log("success");
console.log(data);
})
.catch(e => {
console.log("something went wrong");
console.log(e);
});
}
function secondThunk() {
return new Promise((resolve, reject) => {
axios
.get("https://swapi.co/api/people/")
.then(people => {
someOtherAsyncFunction().then(planets => {
const response = {
planets: planets,
people: people
};
resolve(response);
});
})
.catch(e => {
reject(e);
});
});
}
function someOtherAsyncFunction() {
return axios.get("https://swapi.co/api/planets/").then(response => {
return response;
});
}
mainThunk();
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 })
);
}
Due to the api of a plugin I'm using not working properly. I need to merge the two different requests. I am using the thunk below.
I can get a response but I cannot seem to check for response.ok, and return the combined data:
export function fetchCategories() {
const firstPage =
"http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/categories?per_page=60&page=1";
const secondPage =
"http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/categories?per_page=60&page=2";
return dispatch => {
dispatch(isLoading(true));
Promise.all([fetch(firstPage), fetch(secondPage)])
.then(response => {
// check for ok here
response.ForEach(response => {
if (!response.ok) throw Error(response.statusText);
});
dispatch(isLoading(false));
return response;
})
.then(response => response.json())
// dispatch combined data here
.then(data => dispatch(fetchSuccessCategories(data)))
.catch(() => dispatch(hasErrored(true)));
};
}
Any ideas?
You are doing the check for .ok fine because it's in a loop, but your response is actually an array of two Response objects, it does not have a .json() method. You could do Promise.all(responses.map(r => r.json())), but I would recommend to write a helper function that does the complete promise chaining for one request and then call that twice:
function fetchPage(num) {
const url = "http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/categories?per_page=60&page="+num;
return fetch(url).then(response => {
if (!response.ok)
throw new Error(response.statusText);
return response.json();
});
}
export function fetchCategories() {
return dispatch => {
dispatch(isLoading(true));
Promise.all([fetchPage(1), fetchPage(2)]).then(data => {
dispatch(isLoading(false));
dispatch(fetchSuccessCategories(merge(data)));
}, err => {
dispatch(isLoading(false));
dispatch(hasErrored(true));
});
};
}
I'm building an app to get some events from facebook, take a look:
EventComponent:
events: Object[] = [];
constructor(private eventService: EventService) {
this.eventService.getAll()
.subscribe(events => this.events = events)
}
EventService:
getAll() {
const accessToken = 'xxxxxxxxxxx';
const batch = [{...},{...},{...},...];
const body = `access_token=${accessToken}&batch=${JSON.stringify(batch)}`;
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json())
}
AuthenticationService:
getAccessToken() {
return new Promise((resolve: (response: any) => void, reject: (error: any) => void) => {
facebookConnectPlugin.getAccessToken(
token => resolve(token),
error => reject(error)
);
});
}
I have a few questions:
1) How can I set an interval to update the events every 60 seconds?
2) The value of accessToken will actually come from a promise, should I do something like this?
getAll() {
const batch = [{...},{...},{...},...];
this.authenticationService.getAccessToken().then(
accessToken => {
const body = `access_token=${accessToken}&batch=${JSON.stringify(batch)}`;
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json())
},
error => {}
);
}
3) If yes, how can I also handle errors from the getAccessToken() promise since I'm returning just the Observer?
4) The response from the post request will not return an array of objects by default, I'll have to make some manipulation. Should I do something like this?
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json())
.map(response => {
const events: Object[] = [];
// Manipulate response and push to events...
return events;
})
Here are the answers to your questions:
1) You can leverage the interval function of observables:
getAll() {
const accessToken = 'xxxxxxxxxxx';
const batch = [{...},{...},{...},...];
const body = `access_token=${accessToken}&batch=${JSON.stringify(batch)}`;
return Observable.interval(60000).flatMap(() => {
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json());
});
}
2) You could leverage at this level the fromPromise function of observables:
getAll() {
const batch = [{...},{...},{...},...];
return Observable.fromPromise(this.authenticationService.getAccessToken())
.flatMap(accessToken => {
const body = `access_token=${accessToken}&batch=${JSON.stringify(batch)}`;
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json())
});
}
3) You can leverage the catch operator to handle errors:
getAll() {
const batch = [{...},{...},{...},...];
return Observable.fromPromise(this.authenticationService.getAccessToken())
.catch(() => Observable.of({})) // <-----
.flatMap(accessToken => {
const body = `access_token=${accessToken}&batch=${JSON.stringify(batch)}`;
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json())
});
}
In this case, when an error occurs to get the access token, an empty object is provided to build the POST request.
4) Yes sure! The map operator allows you to return what you want...
Put the event inside a timeout block and set the interval of 60s. setTimeout(() => {},60000).
Using Template string is totally fine but you're telling its value comes from a promise. If your whole block of code is inside resolve function of promise this should fine. So it depends on where your code is. And why promises .In A2 it's recommended to use Observables and not promises. Don't mix them.
You're not returning anything in the error function. So if you return error from that block you'll get error data in case of error. error => erroror error => { return error; }.
Exactly you should you map to get the response and manipulate it and return just the array from that function. .map(resp => { return resp.array}). Since respons is in JSON format now you have to get array from it and return it. you can do as much modifications you want before returning it.
Feel free to edit the answer...