gpt4 book ai didi

javascript - Node.js promise q 未按预期工作

转载 作者:行者123 更新时间:2023-11-28 19:31:16 25 4
gpt4 key购买 nike

这是我的方法:

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(...发送的promise没有收到完整的错误我需要改变什么才能让它发挥作用?

最佳答案

deferred.reject(new Error({error: error, response: response, body: body}));

Error 构造函数接受字符串参数,而不是对象。传入字符串以外的任何内容都会导致参数转换为字符串,对于普通对象来说是[object Object]。由于错误对象没有任何可枚举属性,因此 JSON.stringify 会生成 {}。您需要的是将字符串传递给 Error 构造函数并访问消息属性。

拒绝:

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 添加它是为了支持长堆栈跟踪。

关于javascript - Node.js promise q 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26731849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com