jeudi 22 décembre 2016

How to handle promises in js?

I have always had trouble dealing with promises. I want to understand how they really work (apart from the basic notion of a resolve and reject state). Consider the following piece of code:

var express = require('express');
var app = express();

var Parse = require('parse/node')


Parse.initialize("app");
Parse.serverURL = 'http://localhost:1337/parse'


app.get('/', function(req, res) {
    var GameScore = Parse.Object.extend("GameScore");
    var query = new Parse.Query(GameScore);
    query.equalTo("cheatMode", true);

    ret_stuff = query.find();

    ret_stuff.then(function (result) {
        console.log(result); //prints the right result
        res.json(result); // doesn't happen at all. WHY ? :(
    });

  res.json({"mess": "It shouldn't be here"})
});

app.listen(7001);

app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.status(500).send('Something Broke!');
});

even if I define the find method like this:

    query.find({
        success: function(results) {
            ret = results.map(function(gs) {
                return gs.toJSON();
            });
            console.log(ret)// prints the right result
            res.json(ret) //never happens.  WHY ???
        },
        error: function(error) {
            res.send("Error: " + error.code + " " + error.message);
        }
    });
    res.json({"mess": "It shouldn't be here"})




Aucun commentaire:

Enregistrer un commentaire