-2

I'm runningif-else block of code as shown below :

if (condition){
    var id = data1.id ;
}
else
   var id = data2.id ;

And i'm using this id for some other operation as :

if (id==some value){
   do something ;
}

The above operation is performed when a user registers to the application or if the already logged in user wants views a certain page. Since, node.js is asynchronous, when the user register and the result is stored in database, the id field is undefined and in the 2ndif condition the value of id becomes undefined. But if the user is already logged in this works perfectly as there is not much time consuming operation done. So can anyone suggest me some way to resolve the above issue. Any help or guidance will be highly appreciated.

scrpaingnoob
  • 157
  • 2
  • 12
  • callbacks probably. probably a duplicate of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call?rq=1 – Kevin B Jun 13 '17 at 20:42
  • Sounds like you need to put the second check in the callback of the function that sets the id. – dlsso Jun 13 '17 at 20:43

1 Answers1

0

If any part of your function or if statement is asynchronous, then you need to design the whole function to be asynchronous and return a result either via a callback or via a returned promise. Then, even if the if statement doesn't need to do something asynchronous, you still return the value asynchronously so the caller always gets the response the same way regardless of how it was retrieved. Promises are great for this.

Here's a typical function that handles either a synchronous result or an asynchronous result by designing for an asynchronous result by returning a promise that resolves with the value.

let cache = {};

function getValue(key) {
    // check cache to see if we already have the value
    let val = cache[key];
    if (val !== undefined) {
        // already have value, return promise that resolves with this value
        return Promise.resolve(val);
    } else {
        return new Promise(function(resolve, reject) {
            db.getValue(key, function(err, val) {
                if (err) {
                    reject(err);
                } else {
                    // save value in cache
                    cache[key] = val;
                    resolve(val);
                }
            });
        });
    }
}

getValue(someKey).then(function(val) {
    // use val here whether it was in the cache or not
}).catch(function(err) {
    // handle error here
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979