Search code examples
javascriptnode.jsecmascript-6promisees6-promise

Why my promise not replacing data in constructor?


Please let me know where I am doing mistake. I have class with constructor and 2 methods. I want that method find() will push data from query to array. I don't understand where I am loosing array values and it's empty for other method or just checking value.

class DeleteOffers {

    constructor()
    {
        this.index = 'index';
        this.array = [];
        this.body = {
            query: {
                range: {
                    date_end: {
                        gt: format.asString('yyyy-mm-dd', new Date()),
                        format: "yyyy-mm-dd"
                    }
                },
            },
            _source: "_id"
        };
    }

    find() {
        return client.search({index: this.index, body: this.body})
            .then(response => {
                var that = this;
                return response.hits.hits.map(value => that.array.push(value._id))
            })
            .catch(error =>
                console.log(error.message)
            )

    }

    remove() {
        console.log(this.array); // WHY IT'S EMPTY?
    }

}

const object = new DeleteOffers();
object.find(); // []
object.remove(); // []
return res.json(object.array); // []

Solution

  • You just have to await the find operation:

     (async function() {
        const object = new DeleteExpiredRentalOffers();
        await object.find();
        object.remove();
    })();
    

    or:

     const object = new DeleteExpiredRentalOffers();
     object.find().then(() =>  object.remove());