Wednesday, February 14, 2018

Synchronizing the Asynchronous - Controlling the flow in ascynchronous type of apps

You have certain process to run in sequence; for instance
1. Login into the system
2. Check if the user valid, user status is valid, user role is valid
3. Store for future references
4. Capture audit trail and set timing, menu etc
5. Finally, show correct page base on user role and preferences

This shall be ok in synchronize programming. However, for programming like javascript, js, etc., you may face issues such as null value on a certain process, invalid id, or pages, etc.

There is ways, 'easy' way, but there is no guarantee that the data you will be receiving is accurate or at the exact time you need it.

Example of easy way is using timeout, as shown below

setTimeout(() => {
resolve('success');
}, 100)


Yet, the above example may not resolve your issues entirely.

Another option that looks promising is using Promise. However, there is a drawback to it. Your program may continue waiting despite it is already completed. Although it is a promise, within promise is still asynchronous program run.

return new Promise( (resolve, reject) => {
if (user) {
console.log("getUserProfile() - Success getting user in "
+ JSON.stringify(user) );
resolve(user);
} else {
this.showError('Access Denied! Invalid User Access');
reject('Access Denied! Invalid User Access');
}
});

Take for example the above code. The console may run after resolve(user) as the JSON.stringify may take few seconds than just return resolve value.

So, what is the best solution. Actually, there are no better solutions. What I did was,
1. Rewrite the code and logic and ensure all setting was done prior to user validation and page movement.
2. You can use Reducer or Promise-Sequential

You may refer here:

  1. https://blog.risingstack.com/node-hero-async-programming-in-node-js/
  2. https://forum.ionicframework.com/t/how-can-i-use-promise/40469/3
  3. https://www.promisejs.org/
  4. https://javebratt.com/wtf-promise/
  5. http://coenraets.org/blog/2016/02/angular2-ionic2-data-services-promises-observables/https://stackoverflow.com/questions/47767654/ionic-3-typescript-promise


For me, I'm using the latter (with timeout) as the former implementation is a bit complicated compared to the latter.

Here how I resolve the problem:
var sequential = require('promise-sequential');
var array = [this.getUserProfile(),this.validateUser()];

sequential(array.map((item) => {
return function(previousResponse, responses, count) {
return new Promise(resolve => {
setTimeout(() => {
resolve('success');
}, 100)
})
}
}))
.then(res => {
this.doLogin()
})
.catch(err => {
console.log('loginWithPromise(): ' + err );
this.showError(err);
})

wallawei!!! Hope it helps :)

0 comments :

Share It

Gadget

This content is not yet available over encrypted connections.

Popular Posts