user2924127
user2924127

Reputation: 6242

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');
    });

Upvotes: 4

Views: 6892

Answers (2)

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

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

Upvotes: 6

Shanoor
Shanoor

Reputation: 13662

You're doing it wrong, did you read any documentation about promises? First of all, you don't need an extra package, nodejs already includes Promise.

If asyncMethod is a promise, you can do this directly:

var promise = asyncmethod(some_var);

promise.then(function (sv) {
    console.log(sv + ' Yes it worked');
}, function (em) {
    console.log(sv + ' No it failed');
});

Upvotes: -1

Related Questions