Search code examples
javascriptnode.jses6-promise

nodejs promise wrong usage


Environment: node v5.1.0 on Windows7.

I'm trying to send data to publish_url using post. I would like to run another function in the catch of the init or the then. But don't reach those parts.

The prints "call to success handle func" and "call to failed handle func" isn't being called.

Please advise me in what I'm doing wrong?

var request = require('request');
var publish_url = "https://some_server.com";
function publish_data(url, data) {
    return new Promise(function (resolve, reject){  
        request.post(
            url,
            { json:
                {"handshake":{"data":data}}
            },
            function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    console.log(body);
                    resolve(body);
                } else {
                    console.log("Error:",body);
                    reject(body);
                }
            }
        );
    });
}

function init(){
     console.log("init 1");
     try{
        publish_data(publish_url, 5).then(
            function(obj){
                console.log("call to success handle func");
            });

     }catch(e){
        console.log("call to failed handle func");      
     }

     console.log("init 3");
}

console.log("start");
init();
console.log("end");

Solution

  • Don't use try-catch

    Promises works that way:

    publish_data(publish_url, 5).then(function(obj){
     console.log("call to success handle func");
    }).catch(function(data){
     console.error(data);
    });
    

    Here's a simple example of JS promise:

    function firstFunct(){
     return new Promise(function(resolve,reject){
      data = 5;
      if(data == 5) resolve(data);
      else reject(data);
     })
    }
    
    firstFunct().then(function(data){
      console.log("Resolved, data expected to be 5:" + data); // if Promise is resolved
    }).catch(function(data){
      console.error("Rejected, data is not 5:" + data) // if Promise is rejected
    });