[英]nodejs promise wrong usage
环境:Windows7上的节点v5.1.0。
我正在尝试使用post将数据发送到publish_url
。 我想在init
或者then
的catch中运行另一个函数。 但是不要到达那些部分。
没有调用打印“调用成功句柄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
Promise以这样的方式工作:
publish_data(publish_url, 5).then(function(obj){
console.log("call to success handle func");
}).catch(function(data){
console.error(data);
});
这是一个简单的JS承诺示例:
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 });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.