从Node.js中的Promise(Bluebird)返回值 [英] Returning values from Promise(Bluebird) in Node.js

查看:88
本文介绍了从Node.js中的Promise(Bluebird)返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Node.js,并正在查看Promise模块.我对此很陌生,所以请不要使用不好的代码约定和内容.我正在尝试使用Restify构建REST客户端API.我在下面附加了我的客户代码:

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:

这是我的客户:

// 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 .:我尝试使用Promise.promisifyAll(require('restify')),但它不断抛出一些错误,指出fn不是以这种方式强制使用Promise的函数.

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.

推荐答案

首先,执行此操作时不会出现此类错误:

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

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

第二,不幸的是,restify在导出模块时会使用一些奇怪的吸气剂,因为吸气剂会(而且确实)有副作用,promisifyAll不会访问它们,因此单行魔术将无法正常工作.您需要手动使这些类散布,例如

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);

然后您将呼叫:

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

   });

这篇关于从Node.js中的Promise(Bluebird)返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆