Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs promise not working as it should?

I am using nodejs and the library Promises/A+ (Chose this one as it seems to be the most popular) https://www.npmjs.com/package/promise. The problem I am facing is even though the async function is completing as it should, it is completing after the failure statement. So sv + ' No it failed' is always printed before a console.log message (which indicated it was successful) I have in the async method. This console.log message should be printed before as it is inside of the async method. I am stuck why this happening? The promise always runs as it failed even though the async method return as it has succeeded?

My Code:

 var promise = new Promise(function (resolve, reject) {

        var u = asyncmethod(some_var);

            if (u){
                resolve(some_var)
            }
            else{
                reject(some_var);
            }
    });


    promise.then(function(sv) {
        console.log(sv + ' Yes it worked');
    }, function(em) {
        console.log(sv + ' No it failed');
    });
like image 644
user2924127 Avatar asked Oct 15 '25 16:10

user2924127


1 Answers

Problem in your asyncmethod, it should be async function

var promise = new Promise(function (resolve, reject) {
     //var u = asyncmethod(some_var); // <-- u is not defined, even if you return result stright, as it's the nature of async

     asyncmethod(some_var, function(err, result){ //pass callback to your fn
         if(err){
             reject(err);
         } else {
             resolve(result);
         }
     });
});
promise.then(function(successResponse) { //better name variables 
     console.log(successResponse + ' Yes it worked');
}, function(errorResponse) {
     console.log(errorResponse + ' No it failed');
});

//and simple implementation of async `asyncmethod`
var asyncmethod = function(input, callback){
    setTimeout(function(){
        callback(null, {new_object: true, value: input});
    }, 2000); //delay for 2seconds
}

Notice: as the name implies, this answer considers that asyncmethod is async

like image 175
Medet Tleukabiluly Avatar answered Oct 18 '25 05:10

Medet Tleukabiluly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!