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(() => {
}, 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) );
} 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:


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( => {
return function(previousResponse, responses, count) {
return new Promise(resolve => {
setTimeout(() => {
}, 100)
.then(res => {
.catch(err => {
console.log('loginWithPromise(): ' + err );

wallawei!!! Hope it helps :)


Share It

Popular Posts