javascript - 如何定义一个将 Promise 返回到 Express Route 函数的函数?
问题描述
我有一个名为“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
看起来 Promise 是空的,或者从一个response
对象到另一个对象的 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);
})
抛出了完全相同的错误。
解决方案
您需要getLocations
返回一个Promise
. 目前,它正在运行a fetch
,但它fetch
没有连接到其他任何东西,并且getLocations
正在返回undefined
(当然你不能.then
调用uundefined
)
相反,改为:
const db_location = {
getLocations: function() {
return fetch( ...
此外,由于您没有在getLocations
catch
块中做任何特别的事情,您可能会考虑完全省略它并让调用者处理它。
推荐阅读
- c# - .Net core 3:Microsoft.Extensions.Logging.Internal 中不存在命名空间 internal
- node.js - Angular with node.js http失败响应未知url):0未知错误
- java - 如何使用 SXSSF Streaming api 编辑现有的大型 excel 文件
- android - 杀死应用程序后我的工作经理不工作
- reactjs - React Hot Reloading + Webpack 没有 Express 或 Webpack-Dev-Server
- clang - 使用 wasi-libc 时 fopen 失败
- python-3.x - Pandas 用另一列中的值替换列中的值,但保留一些值
- methods - .aidl 文件中的方法是否有“@Deprecated”注释?
- angular - Google 登录错误 - 用户取消登录或未完全授权
- ios - 无法调整 uicollectionview 高度