[英]Node.js promise with q not working as expected
這是我的方法:
var q = require('q');
var request = require("request");
exports.route = function (req, res) {
var userId = req.query.userId;
if (!userId) {
res.send(JSON.stringify({
errorCode: 400,
error: "userId is missing, please form your query like <url>/avatar?userId=00.42.1"
}), 400);
return;
}
getAvatar(userId).then(function (success) {
console.log('success');
res.json(success);
}, function (error) {
console.log('error');
res.json({error: error});
}
);
};
function getAvatar(userId) {
var isErrorInResponse = function (error, response) {
return typeof error !== 'undefined' || error == null || response.statusCode > 202;
};
var deferred = q.defer();
var url = "http://localhost/avatar" + userId;
console.log(url);
request(url, function (error, response, body) {
if (isErrorInResponse(error, response)) {
deferred.reject(new Error({error: error, response: response, body: body}));
} else {
deferred.resolve(body);
}
});
return deferred.promise;
};
GET localhost:8090/avatar?userId=42 produces
以下日志:
http://localhost/avatar/42
error
並將此響應發送給客戶端:
{
"error": {}
}
這是我的版本,無法更新:
"dependencies": {
"consolidate": "0.9.0",
"express": "3.1.0",
"multipart-parser": "0.0.2",
"mustache": "0.7.2",
"poplib": "0.1.5",
"q": "0.9.3",
"q-io": "1.6.x",
"request": "2.27.0",
"string": "^2.2.0",
"xml2js": "0.2.8"
}
問題是,為什么諾言沒有收到完整的錯誤,我在deferred.reject(...
發送,我需要更改什么才能使它起作用?
deferred.reject(new Error({error: error, response: response, body: body}));
Error
構造函數采用字符串參數,而不是對象。 傳遞除字符串以外的任何內容都會導致參數轉換為字符串,對於普通對象而言,該參數為[object Object]
。 由於錯誤對象沒有任何可枚舉的屬性,因此JSON.stringify
將得到{}
。 您需要將字符串傳遞給Error
構造函數並訪問message屬性。
拒絕:
deferred.reject(new Error(error));
響應:
getAvatar(userId).then(function (success) {
console.log('success');
res.json(success);
}, function (error) {
console.log('error');
res.json({error: error.message});
}
);
如果希望錯誤消息成為對象,則必須對其進行字符串化。 或者,您可以將這些屬性顯式添加到錯誤對象,並且當錯誤為JSON
.stringified時將顯示它們,但這也將顯示stack
屬性,因為Q
添加了它以支持長堆棧跟蹤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.