简体   繁体   中英

NodeJS - Create a Promise function that use Sequelize function

I am new to Promise and I have difficulty creating a Promise that will include a Sequelize function which already uses Promise.

I would like to something like this:

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

How can I make the above pointsToGeoJSON function to use Promise, in order to be able to use .then()

You already have Promises so just do this: 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);

                    });
            });
        });
    }
};

See the link @bergi provided for an explanation of using Promises with callbacks and some alternatives.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM