Nodejs array still empty after pushing objects

I have two REST routes, one use the CarManagerModel to to add a car and another one to delete a car

class CarManagerModel {
    constructor() {
        this.carList = [];
        this.nextCarID = 1;
    }

    async addCar(carDescription) {
        return new Promise(async (resolve, reject) => {
            const car = new Car(this.carID);
            const res = car.setup(carDescription);
            this.nextCarID += 1;
            this.carList.push[car];
            resolve(res);
        });
    }

    async deleteCar(carID) {
        return new Promise(async (resolve, reject) => {
            try {
            console.log("CAR LENGTH: ", this.carList.length)
            console.log("NEXT CAR ID: ", this.nextCarID)
            } catch (error) {
                reject(error);
            }
        });
    }

}
module.exports = new CarManagerModel(); 

I use the CarManagerModel in this way

const CarManagerModel = require('../CarManagerModel');

CarManagerModel.addCar(desc)
CarManagerModel.deleteCar(id)

The problem is when I try to delete a car, this.carList is always empty. However this.nextCarID is correctly incremented.

I tried to use that, I also tried to push simple string, but the array still empty. Any idea?

const that = this before the 
return new Promise(async (resolve, reject) => {
this.carList.push["test"];

Answer

why are your functions async and using promises? there is nothing asynchronous happening in them? You either need to get rid of all the promises / async stuff because its not needed, or else await your CarManagerModel.addCar(desc)

await CarManagerModel.addCar(desc);
await CarManagerModel.deleteCar(id);

Also, this.carList.push[car] is not valid syntax, it’s this.carList.push(car)

I’ve simplified your example a little as I don’t know what Car is, but it runs here – https://www.typescriptlang.org/play?noImplicitAny=false&useJavaScript=true#code/FDDGBsEMGdoAgMKQE4FlIDtIHMCmaB7AE13DgG9g5q5QCNoAXZAV1EYOQAoBKCqmoMYALAJbQAdKBQAZcYzgBeOAG0AugG4Bg6iPESMuAB6MkyAJIARJXACMWwQF8QgmAE8MoOJCJEzXaWRLXGhQZFEAB0ZRej5KHRpkXEYWZAw4QwB3OAAFZAIAW3FcLndPOC4k6AJwADdcABo4JIArXHY+RQA+fgSEugYFQJtyZz6dPUlDEzMrOABqZXttcbhJqVl5CQiWaGEAlB4HVeoqmvqD5COVp2unFxoyrxJwZNx-QKs4m8Tk1PSsrl8kVoCUnhUznVGs1cG0OkoevETmtkG5esiBtVXhJwARsFwAEQIACCACU4DIAKIAOQA4gAVAASAC44ASmutAnImDjcBhsCIeD9+vQsbgcXjCdTKQANemIMlwKys9lrMRTYymFBfYU6Ry0SCMUDCCr4fJXdHI35wxhcM2cO7IsZ9RyO6jOYAezFDFDoLB4QgvGyAsx+nD4VDEUi8LTAUrQDxeXgI-iQTKQUQ+tCYcOB0gSHx+FBcADkADMCAQS0K0xms2GA5GXhIXm9-LYha7eCAQEA

Leave a Reply

Your email address will not be published. Required fields are marked *