Wait for Asynchronous Functions to Finish in Angular

wait for asynchronous functions to finish in Angular

You can use basic promises with async/await.

async ngOnInit() {

await this.getUserProfile(); // <-- 1. change

// my-workplace depends on a private group and we need to fetch that group and edit
// the group data before we proceed and get the group post
if (this.isItMyWorkplace) {
this.getPrivateGroup();
}
this.loadGroupPosts();
}

async getUserProfile() {
this._userService.getUser()
.subscribe((res) => {
this.user = res.user;
console.log('log user', this.user);
this.profileImage = res.user['profile_pic'];
this.profileImage = this.BASE_URL + `/uploads/${this.profileImage}`;
return true; // <-- this
}, (err) => {
this.alert.class = 'alert alert-danger';
if (err.status === 401) {
this.alert.message = err.error.message;
setTimeout(() => {
localStorage.clear();
this._router.navigate(['']);
}, 3000);
} else if (err.status) {
this.alert.class = err.error.message;
} else {
this.alert.message = 'Error! either server is down or no internet connection';
}
throw err;
});

}

Waiting for asynchronous functions in Angular 6

Is the solution to return a promise all the way and set await on every function?

Yes (but note that you don't need to do it explicitly as you have in getAccessToken, more below). If a function relies on the result of an asynchronous function, then that function must also be asynchronous. This bubbles all the way up.

If you want mainFunction to process step1, step2, and step3 in order, and they rely on asynchronous results, then they must be asynchronous, and mainFunction must be asynchronous (and anything using it must be asynchronous):

async function mainFunction() {    console.log("mainFunction start");    await step1();    console.log("step1 done");    await step2();    console.log("step2 done");    await step3();    console.log("step3 done");    console.log("mainFunction done");}async function step1() {    await getData();}async function step2() {    await getData();}async function step3() {    await getData();}async function getData() {    await getAccessToken();    return Math.floor(Math.random() * 1000);}async function getAccessToken() {    await asyncStandIn();}function asyncStandIn() {    return new Promise(resolve => setTimeout(resolve, 800));}
// Top level entry(async () => { mainFunction();})().catch(error => { console.error(error);});

Executing asynchronous functions in order, and waiting for for every function to be finished

This is a trivial async/await case. Since you're already using async, you're missing the awaits. Something like this will do:

public async init(): Promise<void> {
try {
await this.executeFunction1();
await this.executeFunction2();
await this.executeFunction3();
await this.executeFunction4();
await this.executeFunction5();
} catch (error) {
this.log.error(`Init failed`);
}
}

This kind of programming is the prime reason why async/await was introduced, to facilitate async calls in a pseudo sync way.

wait function to finish in Angular

Use await or thenable method:

this.dropzone.saveAttach(data.body[0].id)
.then(() => {
this.router.navigate(['/pages/sending']);

});
})


public saveAttach => async(id: string) {
return new Promise(resolve => {
let latt: Attachement[] = new Array<Attachement>();
this.dropzoneservice.getDoc({
page: 0,
uuid: localStorage.getItem('uuid'),
sort: ['id']
}).subscribe((res: HttpResponse<IDocTemp[]>) => {
for (let i = 0; i < res.body.length; i++) {
let att = new Attachement();
att.idDoc = res.body[i].id.toString();
att.filename = res.body[i].filenamedoc;
att.id = id;

latt.push(att)
}
this.dropzoneservice.addAtt(latt).subscribe(data => {
console.log("save saveAttach : ", data.body);
resolve(); // <------------------
})
});
})
}

Angular Wait for boolean function to finish

.then indicates ref.get is an async function. You can't wait for async functions. You can only return the Promise returned from it or a new one that is properly chained, and pass another callback on the callers site to execute code when the promise completes:

isAdmin(user: any): Promise<boolean> {
var col = this.afs.collection('admins');
var docRef = col.doc('mini-admins');
// vvv added return
return docRef.ref.get().then(function (doc) {
return doc.data().user == user;
}).catch(function (error) {
console.log("Error getting document:", error);
});
}

and then use it like

this.isAdmin(user).then(response => {
if(response) {
...
} else {
...
}
});

Angular - Wait for function call to finish, to proceed with code

Simply convert Observable to a Promise with toPromise() and await them inside async function (used an IIFE as it seems logical in your context):

(async function() {
if (usingSynonum) {
await this.getCollisionsList(i, idOfSyn);
} else {
await this.getCollisionsList(i, listOfAllMeds2[j].id);
}
console.log(...)
})();

...

getCollisionsList(i, id) {
let interactions: Array<DrugInteraction> = new Array<DrugInteraction>();
let dataa = {};
return this.httpClient.getInteractionById(id).toPromise().then(
data => {
... work with your response

And do not subscribe if you return toPromise().

I havent finished the snippet, because you indentations are messed up, but you have all the necessary code here.

Wait my functions finish to return my value Angular

use rxjs operator

interface Menus {
leftMenu: {title: string, id: string, role: string}[];
rightMenu: {icon:string,tooltip: string, id: string, role: string}[];
}

in class

initMenu(es: string): Menus {
return es === '04840' ?
{
leftMenu: [
{title: 'Title 1', id: '1', role: '/URL1'},
{title: 'Title 2', id: '2', role: '/URL2'},
],
rightMenu: [
{icon:'profile',tooltip:'Profile', id:'profile', role:'/'},
]
} :
{
leftMenu: [
{title: 'Title1', id: '1', role: '/URL1'},
],
rightMenu: [
{icon:'profile',tooltip:'Profile', id:'profile', role:'/'},
]
};
}

getMenu(): Observable<Menus> {
this.loginService.recupConnectedUser().pipe(
map(value => {
this.User = value;
this.menu = this.initMenu(value.es);
return this.menu;
})
);
}


Related Topics



Leave a reply



Submit