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

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


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

Need Your Help

Plot points using paint(g) and run()

java user-interface paint runnable

What I want to do is once I pressed the button "GO", it will paint/draw 3 ovals with different coordinates. I've tried repainting but seems it doesn't work. It only shows one oval which is the last...

Understanding client/server relation c++

server client chat

I want to build a simple client/server application that allows two different computers to send messages back and forth, i.e. some type of chat messenger. What I'm having trouble understanding is ho...