NodeJS - 创建一个使用 Sequelize 函数的 Promise 函数
NodeJS - Create a Promise function that use Sequelize function
我是 Promise 的
新手,我很难创建一个包含已经使用 Promise 的 Sequelize 函数的 Promise。
我想要这样的东西:
var geojson = require(path.join(__dirname, 'lib', 'geojson');
router.get('/[0-9]{3}/points.geojson', function(req, res, next){
var codecs = req.url.split('/')[1];
geojson.pointsToGeoJSON(codecs).then(function(geoJSON){
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(geoJSON));
});
});
./lib/geojson.js:
var path = require('path');
var Promise = require('promise');
var Geojson = require('geojson');
var Point = require(path.join(__dirname, '..', '..', 'models', 'point'));
module.exports = {
pointsToGeoJSON: function(codecs) {
//this is a Sequelize function
Point.findAll({where: {codecs : codecs}, raw: true})
.then(function(points){
var data = [];
for(var i=0; i < points.length; i++){
points[i].coordinates = JSON.parse(points[i].coordinates);
data.push(points[i]);
}
//this is another asyn function
Geojson.parse(data, {'crs': {'type': 'name', 'properties': {'name': 'EPSG:3857'}}, 'Point': 'coordinates'}, function(geoJSON){
//this is what I want the function to return
return geoJSON;
});
});
}
}
如何使上述pointsToGeoJSON
函数使用承诺,以便能够使用.then()
你已经有了承诺,所以这样做: var 路径 = require('path'); var Promise = require('promise'); var Geojson = require('geojson'); var Point = require(path.join(__dirname, '..', '..', 'models', 'point'));
module.exports = {
pointsToGeoJSON: function(codecs) {
//this is a Sequelize function
return Point.findAll({where: {codecs : codecs}, raw: true}).then(function(points){
var data = [];
for(var i=0; i < points.length; i++){
points[i].coordinates = JSON.parse(points[i].coordinates);
data.push(points[i]);
}
//this is another asyn function
return new Promise(function(resolve, reject){
Geojson.parse(
data,
{'crs': {'type': 'name', 'properties': {'name': 'EPSG:3857'}}, 'Point': 'coordinates'},
function(geoJSON){
resolve(geoJSON);
});
});
});
}
};
请参阅@bergi提供的链接,了解如何将 Promise 与回调和一些替代方案一起使用。
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 如何在JavaScript中将字符串转换为函数引用
- 用嵌套函数和默认函数定义函数
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 无法导出函数expressjs/requestjs中的变量
- 函数参数中的数据与指定变量之间的任何性能差异
- JQuery合并了keyup和focusout两个函数
- ES6构造函数返回基类的实例
- 监视函数从服务返回不起作用,但作用域函数起作用
- 我可以在json对象中添加一个函数吗
- AngularJS:我可以跳过函数参数回调吗
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- NodeJS - 创建一个使用 Sequelize 函数的 Promise 函数
- Node sequelize回调承诺期望一个函数,是否有一种方法可以通过函数调用删除已声明的函数
- 在Sequelize中导入instanceMethods函数时报错
- 如何通过sequelize.js中的函数进行过滤
- Sequelize:调用.get({plain: true}))返回.get不是函数
- 使用Sequelize在列上使用datetime函数