Node.js承诺q不能按预期工作

Node.js promise with q not working as expected

本文关键字:工作 不能按 js 承诺 Node      更新时间:2023-09-26

这是我的方法:

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构造函数并访问消息属性。

拒绝:

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