[英]How to define a function which returns Promise to a Express Route function?
我有一个名为“ 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
对象到另一个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
(当然你不能叫.then
上uundefined
)
改为:
const db_location = {
getLocations: function() {
return fetch( ...
另外,由于您在getLocations
catch
块中没有做任何特别的事情,因此您可以考虑完全省略它,让调用者处理它。
您的函数不返回任何内容。
如果要使用承诺,则需要return
其return
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.