Anita
Anita

Reputation: 506

Why is Promise returned in sequelize

I am new to sequelize. So, I am writing a query where I map the parameters and find them in the db. But all I am getting is a Promise. Here's my code

findData(params) {
   return params.map(product => {
      return Model.Stock.findAll({ raw: true })
        .then(stocks => stocks.map(stock => ({ success: true, data: stock })))
        .catch(err => ({ success: true, error: err.toString() }));
    });
  },

I am hoping to get objects, how do I do that?

0:Promise
_bitField:33554432
_fulfillmentHandler0:undefined
_promise0:undefined
_receiver0:undefined
_rejectionHandler0:Array(4)
_trace:CapturedTrace
__proto__:Object
length:1
__proto__:Array(0)

What should I change in order to return objects?

Upvotes: 0

Views: 1593

Answers (2)

Vivek Doshi
Vivek Doshi

Reputation: 58573

Explanation For ( Why its returning promise ) :

findData(params) {
   return params.map(product => { // <-------- 2. So this will return array of promise objects
      return Model.Stock.findAll({ raw: true }) //<------- 1. This will always returning promise , nature of sequlize
        .then(stocks => stocks.map(stock => ({ success: true, data: stock })))
        .catch(err => ({ success: true, error: err.toString() }));
    });
},

Solution 1 :

Promise.all(findData(params)) // <-------- 3. Use Promise.all to solve all promise and get data from all   
.then(stocs => {
    console.log(stocks); //<----------- 4. console log your out put and you will get idea
});

Solution 2 :

findData(params) {
   return Promise.all(params.map(product => { 
      return Model.Stock.findAll({ raw: true })
        .then(stocks => stocks.map(stock => ({ success: true, data: stock })))
        .catch(err => ({ success: true, error: err.toString() }));
    }));
},

then you can get data like :

findData(params).then(your_data => { ..... })

Upvotes: 0

Amiga500
Amiga500

Reputation: 6131

I would suggest to read a bit about promises, and how to effectively use them. You can find many examples around.

In your particular case, looking at the code, you do receive an object. Take a look at:

.then(stocks => stocks.map(stock => ({ success: true, data: stock })))

Lets break it even more:

stocks => stocks.map

Stocks should (concluding by the name) have an array of objects.

In your case, you could use it as follows:

findData(params).then(function(yourObjects) {

    //do something here...
});

Upvotes: 1

Related Questions