javascript - 如何定义一个将 Promise 返回到 Express Route 函数的函数?

标签 javascript node.js express promise node-fetch

我有一个名为“db_location”的业务级数据库模块,它使用 node-fetch 模块通过 REST API 从远程服务器获取一些数据。

**db_location.js** DB LOGIC

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

const db_location = {
    getLocations: function() {

        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( res1 => {
            //console.log("res1.json(): " + res1.json());
            return res1;
        })
        .catch((error) => {
            console.log(error);
            return Promise.reject(new Error(error));
        })
    }

};

module.exports = db_location

我需要在路由函数中调用此函数,以便将数据库处理与 Controller 分开。

**locations.js** ROUTE

var path = require('path');
var express = require('express');
var fetch = require('node-fetch');
var router = express.Router();

const db_location = require('../db/db_location');

/* GET route root page. */
router.get('/', function(req, res, next) {

  db_location.getLocations()
  .then(res1 => res1.json())
  .then(json => res.send(json["results"]))
  .catch((err) => {
    console.log(err);
    return next(err);
  })
});

当我跑http://localhost:3000/locations时,我收到以下错误。

Cannot read property 'then' of undefined

TypeError: Cannot read property 'then' of undefined

看起来 Promise 是空的,或者从一个 response 对象到另一个对象的 Promise 链中出现了问题?解决这种情况的最佳实践是什么?

编辑 1

如果我更改 getLocations 以返回 res1.json() (根据 node-fetch 文档,我认为这是一个非空 Promise):

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(  res1 => {
       return res1.json();     // Not empty as it can be logged to `Promise Object`
    })
    .catch((error) => {
        console.log(error);
        return Promise.reject(new Error(error));
    })

路线代码更改为:

db_location.getLocations()
  .then(json => res.send(json["results"]))
  .catch((err) => {
    console.log(err);
    return next(err);
  })

抛出了完全相同的错误。

最佳答案

您需要getLocations返回一个Promise。目前,它正在运行一个fetch,但是fetch没有连接到其他任何东西,并且getLocations返回 undefined (当然你不能在 uundefined 上调用 .then)

改为:

const db_location = {
  getLocations: function() {
    return fetch( ...

此外,由于您没有在 getLocations catch block 中执行任何特殊操作,因此您可能会考虑完全忽略它并让调用者处理一下。

关于javascript - 如何定义一个将 Promise 返回到 Express Route 函数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51413042/

相关文章:

javascript - 单击图片元素时切换 img src 和 source srcset

javascript - 多余的花括号

javascript - 是否有任何构建 JSON 消息的指南?

javascript - 使用 JavaScript 创建跳棋游戏

Node.js - 使用 Google Cloud Vision API 从 PDF 文件中提取文本时出现问题

node.js - 如何与 nx 并行运行 express 和 angular?

node.js - Adm zip 将 zip 缓冲区写入 ExpressJS 响应

javascript - "slc start"是怎么判断应该加载哪个js的呢?

node.js - 如何在不连接http服务器的情况下使用连接路由器?

node.js - 在Hapijs中替换expressjs的app.use()方法?