Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise findOneAsync variable = {"isFulfilled":false,"isRejected":false}?

Utilizing Bluebird to Promisfy Mongoose, I have a Promise.map(function with a series of if/else for looping through an array to see if a reference doc exists, else create one..

Assigning the product of findOneAsync to a variable, to then assign 'variable._id' to a new doc in the making (the main promise), the console logs {"isFulfilled":false,"isRejected":false}

Here's a snippet:

for (i=0; i<items.length; i++) {
    var existingItem = Models.Items.findOneAsync({ item: items[i] });
    console.log( "existingItem : ");
    console.log( JSON.stringify(existingItem) );
    console.log( "existingItem._id : " + existingItem._id );

Here's a log:

existingItem : 
{"isFulfilled":false,"isRejected":false}
existingItem._id : undefined

Why might the existingItem variable be pending for the Model.Item.findOneAsync..?

like image 221
Stacks Avatar asked Feb 12 '15 03:02

Stacks


2 Answers

Your question is not really clear, but my question to you would be: why would existingItem not be pending right after you retrieved it?

Do you understand how to use promises? Most of the time you need to get at their resolved values using .then() or other promise manipulation functions:

var existingItem = Models.Items.findOneAsync({ item: items[i] });
existingItem.then(function (value) {
    console.log( "existingItem : ");
    console.log( JSON.stringify(existingItem) );
    console.log( JSON.stringify(value); );
    console.log( "existingItem._id : " + existingItem._id );
});
like image 200
JLRishe Avatar answered Nov 07 '22 05:11

JLRishe


You need to wait until the promise gets resolved (or rejected). You can use any one of the following two ways:

1. By 'awaiting' to get the final state of the promise as follows:

var existingItem = await Models.Items.findOneAsync({ item: items[i] });

2. By handling the promise using '.then' handler as follows:

return Models.Items.findOneAsync({ item: items[i] })
    .then(function(existingItem) {
        console.log("existingItem", existingItem);
like image 31
zlatanned Avatar answered Nov 07 '22 06:11

zlatanned