NodeJS - 创建一个使用 Sequelize 函数的 Promise 函数

NodeJS - Create a Promise function that use Sequelize function

本文关键字:函数 Sequelize 一个 Promise 创建 NodeJS      更新时间:2023-09-26
我是 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 与回调和一些替代方案一起使用。