【问题标题】:Unable to fetch object value and define constant and static variable in class无法获取对象值并在类中定义常量和静态变量
【发布时间】:2019-01-24 01:30:17
【问题描述】:

我有以下代码:

'use strict';

const Request = require('request');

class CryptoKetHandlers {

    static async coins(ctx) {
        try {
            var CONTENT_TYPE = 'application/json';
            console.log(`## Hitting cryptoket coins api for coins list ...`);
            var res = await Request.get({
                url: 'https://api.cryptoket.io/info/currencies',
                headers: {
                    'Content-Type': CONTENT_TYPE,
                }
            }, (err, res, body) => {
                //console.log(`Inside response ... res: ${res} err: ${err} body: ${body}`);
                if (err) {
                    console.log(`#### ERROR :: API RESP :: CryptoKetHandlers :: coins :: exception :: ${err}`);
                    ctx.throw(500);
                } else {
                    let res = {};
                    res.body = body;
                    res.status = 200;
                    return res;
                }
            });
        } catch (ex) {
            console.log(`#### ERROR :: CryptoKetHandlers :: coins :: exception :: ${ex}`);
            ctx.throw(500);
        }
        console.log(`######### Final Response :: status - ${res.status} body - ${res.body} res :: ${res}`);
        ctx.body = res;
        ctx.status = 200;
    }

}

module.exports = CryptoKetHandlers;

我来自 Java 背景,是 koa 和 nodejs 的新手,所以想知道如何才能实现以下目标:

  1. 为什么 res.status 和 res.body 总是返回 undefined?
  2. 如何将 CONTENT_TYPE 声明为应该是 const & static 的类变量?

想要实现的是:

  • 从 Request.get 中返回所有这些 err、res、body 参数和
    在其他地方(在另一个类函数中)处理它。

    • 使所有可重用的变量类级别,这样就不需要一次又一次地定义。
    • 如果您有一些建议可以让我的代码更健壮、更简洁。

我通过谷歌搜索尝试了各种方法,但没有成功,所以在这里问。

提前致谢。

【问题讨论】:

    标签: javascript jquery node.js ecmascript-6 koa


    【解决方案1】:
    1. 为什么 res.status 和 res.body 总是返回 undefined?

    首先,Request.get() 应该返回一个Promise 以使await 工作。

    await 表达式导致异步函数执行暂停,直到 Promise 被解决,即被履行或被拒绝,并在履行后恢复异步函数的执行。 恢复时,await 表达式的值是已实现的 Promise 的值。

    其次,您不小心将返回值 res 替换为 (err, res, body) => {} 中的另一个 res。相反,我们可以将返回值作为普通对象返回。

    进行这些更改,

    'use strict';
    
    let request = require('request');
    
    const CONTENT_TYPE = 'application/json';
    
    function makeRequest() {
      return new Promise((resolve, reject) => {
        request.get({
          url: 'https://api.cryptoket.io/info/currencies',
          headers: {
            'Content-Type': CONTENT_TYPE,
          }
        }, (err, res, body) => {
          if (err) {
            console.log(`#### ERROR :: API RESP :: CryptoKetHandlers :: coins :: exception :: ${err}`);
            return reject(err);
          }
    
          // return as object
          return resolve({ 
            body: body,
            status: 200
          });
        });
      });
    }
    
    class CryptoKetHandlers {
    
      static async coins(ctx) {
        try {
          console.log(`## Hitting cryptoket coins api for coins list ...`);
          let res = await makeRequest();
          console.log(`######### Final Response :: status - ${res.status} body - ${res.body} res :: ${res}`);
        } catch (ex) {
          console.log(`#### ERROR :: CryptoKetHandlers :: coins :: exception :: ${ex}`);
        }
      }
    
    }
    

    因为我用let 替换了var。我已将最终日志移至 tryblock 内。

    1. 如何将 CONTENT_TYPE 声明为应该是 const & static 的类变量?

    目前正在对此提出建议。您可以查看ES6 class variable alternatives了解更多信息。

    【讨论】:

    • @ShivangAgarwal 这是主观的;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2013-04-11
    • 2015-06-02
    • 1970-01-01
    • 2016-03-05
    • 2012-04-17
    相关资源
    最近更新 更多