我正在调用func2(它应该返回promise)但是promise没有得到解决。我错误地解决了promise或者是否还有其他问题。请告诉我以下代码中的问题是什么?
function func1() {
func2().then(function (data) {
console.log(data);
})
}
var func2 = function () {
var d = q.defer();
var postRequest = {
host: "abc",
path: "/xyz",
};
var buffer = "";
var req = http.request( postRequest, function( res ) {
var buffer = "";
res.on( "data", function( data ) {
console.log("data\n");
buffer = buffer + data;
});
res.on( "end", function( data ) {
d.resolve(data);
return d.promise;
});
});
console.log('after req');
req.write(body);
req.end();
};
答案 0 :(得分:3)
您需要在函数的最后返回promise。尝试
function func1() {
func2().then(function (data) {
console.log(data);
}).catch(function (error) {
// Handle any error from all above steps
console.log("Got error:" + error);
})
.done();
}
var func2 = function () {
var d = q.defer();
var postRequest = {
host: "abc",
path: "/xyz",
};
var buffer = "";
var req = http.request( postRequest, function( res ) {
var buffer = "";
res.on( "data", function( data ) {
console.log("data\n");
buffer = buffer + data;
});
res.on( "end", function( data ) {
d.resolve(buffer);
});
res.on( "error", function( err ) {
d.reject(err);
});
});
console.log('after req');
req.write(body);
req.end();
return d.promise;
};