简体   繁体   English

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

[英]Node.js promise with q not working as expected

this is my approach: 这是我的方法:

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 following log: GET localhost:8090/avatar?userId=42 produces以下日志:

http://localhost/avatar/42
error

and sends this response to the client: 并将此响应发送给客户端:

{
  "error": {}
}

And here is my versions, which I'm not able to update: 这是我的版本,无法更新:

 "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"
  }

And the question is, why does the promise not receive the full error, I'm sending at deferred.reject(... and what have I to change so that it will work? 问题是,为什么诺言没有收到完整的错误,我在deferred.reject(...发送,我需要更改什么才能使它起作用?

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

The Error constructor takes in a string argument, not an object. Error构造函数采用字符串参数,而不是对象。 Passing in anything other than a string will result in the argument being converted to a string, which for a plain object is [object Object] . 传递除字符串以外的任何内容都会导致参数转换为字符串,对于普通对象而言,该参数为[object Object] Because an error object does not have any enumerable properties, JSON.stringify ing it results in {} . 由于错误对象没有任何可枚举的属性,因此JSON.stringify将得到{} What you need is to pass in a string to the Error constructor and access the message property. 您需要将字符串传递给Error构造函数并访问message属性。

Reject: 拒绝:

deferred.reject(new Error(error));

Response: 响应:

getAvatar(userId).then(function (success) {
            console.log('success');
            res.json(success);
        }, function (error) {
            console.log('error');
            res.json({error: error.message});
        }
   );

If you want the error message to be an object, you'll have to stringify it. 如果希望错误消息成为对象,则必须对其进行字符串化。 Alternatively, you can explicitly add those properties to the error object and they'll show up when the error is JSON .stringified, but this will also show up the stack property because Q adds it to support long stack traces. 或者,您可以将这些属性显式添加到错误对象,并且当错误为JSON .stringified时将显示它们,但这也将显示stack属性,因为Q添加了它以支持长堆栈跟踪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM