Returning values from Promise(Bluebird) in Node.js

2019-07-10 07:36发布

问题:

I am learning Node.js and was looking at the Promise module. I am very new at this so please bare with bad code conventions and stuff. I am trying to build a REST Client API using restify. I have attached my Client Code below:

Here is my Client:

// local functions
function loadResult(err, req, res, obj) {
    //console.log(err, req, res, obj);
    var result = {
        'err': err,
        'text': obj
    };
    console.log(result);
    return result;
}

function getClient() {
    if (client) {
        return client;
    } else {
        client = restify.createJsonClient(options);
        return client;
    }
};

function RestClient(headers) {

    if (headers) {
        global_headers.Authorization = headers.Authorization || global_headers.Authorization;
        options.headers = global_headers;
    }
};

RestClient.prototype.getClient = getClient;

RestClient.prototype.doGET = function doGET(path) {
    return new Promise(function(resolve) {
        client.get(path, loadResult);
    }).then(function(result) {
        console.log("before final return:" + result);
        return result;
    });
};

// exports
module.exports = RestClient;

In the console when I run the following lines:

var Rest = require('./testRest.js');
var restClient = new Rest();
var client = restClient.getClient();
var data = restClient.doGET('/hello/mark');

I can see the result printed just once on the console. But the Data is just what I believe a Promise. Is there a way for me to get the result in data? Also trying to figure out why the result never got printed the second time.

P.S.: I tried using Promise.promisifyAll(require('restify')) but it kept throwing some error saying fn is not a function which force use Promise in this way.

回答1:

First of all, there is no such error when I do:

var Promise = require("bluebird");
Promise.promisifyAll(require("restify"));

Secondly, restify unfortunately uses some weird getters when exporting the module, as getters can (and do) have side effects, promisifyAll will not visit them, so the one line magic won't work. You need to promisify the classes manually, e.g.

Promise.promisifyAll(require("restify").JsonClient.prototype);

Then you would call:

   client.getAsync(path).spread(function(req, res, obj) {

   });