我是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
函数使用Promise,以便能够使用.then()
答案 0 :(得分:1)
你已经有了Promise所以这样做: 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
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提供的链接,了解使用带回调的Promises和一些替代方法。