0

the console.log(workingWeekdaysVar) line; is outside the findOne's scope, and the variable was declared outside it too, yet it's giving me null ...

when i put console.log(workingWeekdaysVar); inside the findOne's scope, it does give the right output, but this is useless for me because I wanna use workingWeekdaysVar elsewhere below.

The two commented out lines are the 2nd approach i attempted to do, but it gave me an undesirable output because this whole code is inside a complicated for loop.

How can I simply pass the fetched value of workingWeekdaysVar out of the scope?

    var workingWeekdaysVar = [];

                    buyerSupplierFisModel.findOne(filter).then(function (combo) {

                        workingWeekdaysVar = combo.workingWeekdays;

                         //server.getWorkingWeekdays = function () { return combo.workingWeekdays };

                    });

   console.log(workingWeekdaysVar);

//console.log(server.getWorkingWeekdays());

2 Answers 2

1

findOne() is an asynchronous function (it returns a promise object). This means that it returns inmediately and your next code line is run (in this case, console.log(workingWeekdaysVar);. But, since the function isn't done yet, workingWeekdaysVar is empty, and it will be empty until findOne() has done its job and returned the results in the provided chained callback .then(function (combo) {....

So if you want to do anything with the results, you'll have to do it in the callback. One option to this would be to use async / await:

(async () => {
    try {
        const { workingWeekdaysVar } = await buyerSupplierFisModel.findOne(filter)
        console.log(workingWeekdaysVar)
    } catch (e) {
        console.log(`Error: ${e}`);
    }
})()
Sign up to request clarification or add additional context in comments.

Comments

0

Re-arranging your code a bit:

let doToResponse = (combo)=>{
 workingWeekdaysVar = combo.workingWeekdays; 
 console.log(workingWeekdaysVar);
}
 buyerSupplierFisModel.findOne(filter).then(function (combo) {
                        doToResponse(combo)
                    });
  • good for re-usability

My personal favorite:

buyerSupplierFisModel.findOne(filter).then(combo=> {
    workingWeekdaysVar = combo.workingWeekdays; 
    console.log(workingWeekdaysVar);
});

The important thing is keep in mind, as Miguel Calderón says.. findOne - returns a promise. At that point you have another thread with different local (Lexical?) scope

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.