nodejs promise 错误用法

nodejs promise wrong usage

环境:Windows7 上的节点 v5.1.0。

我正在尝试使用 post 将数据发送到 publish_url。 我想运行另一个函数中的catch initthen。 但不要触及那些部分。

未调用输出 "call to success handle func" 和 "call to failed handle func"。

请指教我做错了什么?

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");

不要使用try-catch

Promises 是这样工作的:

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

这是一个简单的 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
});