【问题标题】:How to define a function which returns Promise to a Express Route function?如何定义一个将 Promise 返回到 Express Route 函数的函数?
【发布时间】:2018-12-27 00:35:22
【问题描述】:

我有一个名为“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

我需要在 Route 函数中调用此函数,以便将数据库处理与控制器分开。

**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

从一个response 对象到另一个对象的Promise 链中似乎Promise 是空的或者有什么问题?解决这种情况的最佳做法是什么?

编辑 1

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

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

抛出了完全相同的错误。

【问题讨论】:

    标签: javascript node.js express promise node-fetch


    【解决方案1】:

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

    改为:

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

    另外,由于您在 getLocations catch 块中没有做任何特别的事情,您可以考虑完全省略它并让 调用者 处理它。

    【讨论】:

    • 非常感谢您的回答!我还有一个问题。请参考上面的 EDIT 1。
    • 您的EDIT 1 看起来不像是return 最初的fetch,这正是您将承诺链接在一起所需要的,如答案中所述... ?
    • 是否必须返回初始提取?有没有办法将 response.json() 从 fetch 返回到 route 函数? fetch 调用中的 response.json() 是根据 node-fetch 文档的 Promise。
    • 是的,除了返回 fetch 本身之外,您还需要从 .then 链接在 fetch 之后的 res1.json() 返回 res1.json(),这样getLocations 的消费者可以看到并链接到返回的 Promise 链的末尾。 return fetch
    • 您的意思是返回 res1.json() 并从 getLocations() 函数中获取吗?你能举个例子吗?
    【解决方案2】:

    你的函数没有返回任何东西。

    如果你想使用一个promise,你需要return它。

    【讨论】:

    • 非常感谢!我对代码进行了一些更改,它返回了一个 Promise 对象,但抛出了同样的错误。请参考上面的编辑。
    猜你喜欢
    • 2020-10-03
    • 2017-06-09
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2020-06-20
    • 2020-07-16
    • 2017-09-13
    相关资源
    最近更新 更多