Search code examples
javascriptobjectpromisesequelize.jssequelize-cli

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?


Solution

  • 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 => { ..... })