Sunday 19 March 2017

Promise impaired programmer may be this one question away from breaking through.

I've jerry-rigged something like this to work for me in say a Car class (query builder is knex, model is objection):static async createCar(color) { let returner = 'error creating car' await this .query() .insert({color: color}) .then((newCar) => { console.log(`new ${newCar.color} car created`) returner = newCar }) .catch((error) => { console.log(error) returner = returner + ": " + error }) return returner } Then I can call it elsewhere:await Car.createCar('red') // {color: red} But the more I use and understand promises (understanding admittedly lacking), the more I'm seeing that they should really be handled at the end, or at the last call. So I really want my class method here to be called like this:Car.createCar('red') .then( (car) => console.log(car) ) // or whatever I want to do with the car .catch( (error) => console.log(error) ) But I'm having trouble writing the static method that way.Lastly, how come I can generally console.log() a value from within a .then() statement, but I'm not able to return that console.loggable value outside the then() statement? That's a huge one.

Submitted March 19, 2017 at 11:37PM by coderbee

No comments:

Post a Comment