【问题标题】:How to process the Promise returned from parent Promise chain with various possible outcomes如何处理从父 Promise 链返回的具有各种可能结果的 Promise
【发布时间】:2018-07-23 14:17:41
【问题描述】:

在我的 Node.JS Web 应用程序中,我有一个数据库层模块 (db_location.js)。根据来自 node-fetch 调用的响应类型,它返回一个 json() 或 text() 承诺,具体取决于来自 fetch 调用响应的内容类型。

const querystring = require('querystring');
const fetch = require('node-fetch');

const p_conf = require('../parse_config');

const db_location = {
    getLocations: function() {
        return fetch(`${p_conf.SERVER_URL}/parse` + '/classes/GCUR_LOCATION', { method: 'GET', headers: {
            'X-Parse-Application-Id': 'APPLICATION_ID',
            'X-Parse-REST-API-Key': 'restAPIKey'
        }}).then(function(res1) {           
            const contentType = res1.headers.get('content-type').toLowerCase();
            if (contentType.includes("application/json"))
                return res1.json();  // RETURNS A PROMISE
            else
                return res1.text();  // RETURNS A PROMISE
        }).catch(err => Promise.reject(JSON.stringify({ "Error": err })));
    }

};

module.exports = db_location

该模块由 Express 路由 locations.js 调用。

const db_location = require('../db/db_location');
router.get('/', function(req, res, next) {
    db_location.getLocations()
    .then(function(result) {
        /*
        IF RESULT IS JSON, DO PROCESSING 1;
        ELSE RESULT IS TEXT, DO PROCESSING 2.
        */
    })
    .catch((err) => {
        return next(err);
    })

});

由于 fetch 的响应无法沿承诺链传递,因此无法从路由代码中检索内容类型。

【问题讨论】:

  • 文本代码...无论如何,json 只是文本,所以你总是可以 JSON.parse 任何文本 - 哦,你已经这样做了 - 那么问题是什么?在.then(function(result) { 的主体中检查result 是对象还是字符串 - 简单
  • 在您的代码中阐明您的 cmets ...return res1.json(); // RETURNS A PROMISE THAT RESOLVES TO AN OBJECTreturn res1.text(); // RETURNS A PROMISE THAT RESOLVES TO A STRING

标签: javascript node.js promise


【解决方案1】:

那么 Javascript 字符串是有效的 Json 数据。所以从理论上讲,除非你在 res1.json() 之后转换它,否则你无法真正判断某个东西是否是 Json。

您可以在 location.js 中使用以下内容检查某些内容是否为字符串类型

if(typeof result === 'string'){ /* it's a string*/ }
else{ /* it's something else */}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 2017-12-28
    • 2021-07-23
    相关资源
    最近更新 更多