Domanda

I'm hoping this is a simple thing I'm missing, but I can't seem to return data as I'd like to. My function login takes a username, and returns the password and id for authentication, along with the users XY coordinates from the database.

The XY coordinates are dependent on the ID returned from the login query, which are all returned as a Promise to the main function for authentication. However, I can't seen to return all the data into one nicely knit object.

function login(user) {
    var query = 'SELECT password,id FROM player WHERE name='+mysql.escape(user);
    return db.select(query).then(function(rows) {
        console.log(rows);
        return Promise.all([
            getX(rows[0].id),
            getY(rows[0].id)
        ]);
    });
}

This logs:

[ { password: 'nopasswordforu', //<-- not a real password
    id: 9 } ]
[ [ { x: 32 } ], [ { y: 36 } ] ]

The password is logging from the console statement, not the return. The only thing returned is the xy coordinates. How can I return the query results in the same Promise as the function returns?

È stato utile?

Soluzione

function login(user) {
    var query = 'SELECT password,id FROM player WHERE name='+mysql.escape(user);
    return db.select(query).then(function(rows) {
        // Promise.all is unnecessary if the caller calls .spread()
        return [getX(rows[0].id), getY(rows[0].id), rows[0]];
    });
}

login(...).spread(function(x, y, user){
    console.log(x, y, user.password, user.id);
})

Altri suggerimenti

You could do:

    return Promise.all([
        getX(rows[0].id),
        getY(rows[0].id)
    ]).then(function(xCoord,yCoord) {
      return Promise.all([{
          password:rows[0].password,
          x:xCoord[0].x,
          y:yCoord[0].y
      }]);
    });

The latter piece of code would look something like this:

login('username').then(function(data) {
/* 
 exposed:

 data.password,
 data.x,
 data.y

*/
});

Note that I am making the assumption that getX and getY are async functions here, which is why you are calling Promise.all() around them.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top