1

I want to return the value from sequelize query in another variable. I have to tried different solution, but i have the same result:

    Promise {
  _bitField: 2097152,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _boundTo: SellerPresent }

my js file(at the moment):

function findIdSeller(selectEvent) {
var match = {attribute: ['seller_id'], where: {event_id: selectEvent}, raw: true};
return models.SellerPresent.findAll(match)}

exports.findDataSeller = function (selectEvent) {
    var seller = [];
    return findIdSeller(selectEvent).then(function (result) {
        return  seller.push(result.seller_id)
    })
};

I need export this data in routes. How i can do it?

Kasiriveni
  • 5,671
  • 1
  • 22
  • 31
Gig90
  • 35
  • 5
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Yury Tarabanko Jun 05 '17 at 15:11

1 Answers1

0

First of all, be aware that asynchronous results cannot be treated (or exported) synchronously, so you need to stick with promises all the way.

Secondly, the findAll method will return an array, so you should not access the seller_id on that array, but on its elements. For that you can use map:

function findIdSeller(selectEvent) {
    var match = {
        attribute: ['seller_id'], 
        where: {
            event_id: selectEvent
        }, 
        raw: true
    };
    return models.SellerPresent.findAll(match);
}

// You can export a promise, not the promised value:
exports.findDataSellerPromise = function (selectEvent) {
    return findIdSeller(selectEvent).then(function (result) {
        return result.map(function(seller) {
            return seller.seller_id
        });
    });
});

You need to call findDataSellerPromise as returning a promise. So, for instance, if you need to use the promised data as a response in routing, then call then on it:

app.get('/', function (req, res) { 
    // ....
    findDataSellerPromise(selectEvent).then(function(sellers) {
        res.send(sellers);
    });
});
trincot
  • 317,000
  • 35
  • 244
  • 286