How to work with result of the callback of the fin

2019-05-27 01:26发布

I am using mongoose as ODM for a nodejs-mongodb application.

Is my first nodejs application and I come from a non functional programming background.

Looking at the docs of mongoose you can find:

Kitten.find(function (err, kittens) {
    if (err) return console.error(err);
    console.log(kittens);
});

So great, here we have the find function as part of our model (Kitten) and it actually can find the document and retrieve it inside the callback function as "kittens", and in this case it uses console.log() .

But I want to know how this functional programming is used to assign this value into a variable (because I have this in another file in the models folder and I import the module with require)

I found another question about something similar asking for the ObjectId but they offer the same kind of answer when you use the callback to just use the console.log to print the answer and if we are honest this is not useful.

Since I come from a non functional programming background I was expecting something like:

var kitten = Kitten.find({name:'Silence'}); 

As far as I know if you assign a new variable inside the callback the scope of the variable is just within the callback function, the same with a return variable , even declaring a variable before the method is not gonna work.

Im sure there's something Im missing. This project is so big and I don't think they can't forget to offer a method to do this. I think there is something in the functional programming I am missing or I don't know.

So, how can achieve this ?

Thanks !

Edit: I dont know why the community is saying that my question is a possible duplicate of How to return the response from an asynchronous call? this question is more oriented to js ajax async in general and this question is oriented to a ODM framework and how to handle the result that it can be done through promises too and is a different thing

1条回答
看我几分像从前
2楼-- · 2019-05-27 02:09

I would like to inform you that such kind of operations like accessing your database and retrieving data are async operations, so they are working differently and you can't just assign value like in basic sync operations. In fact that's the main point of Node.js. You may read more if you follow the link: https://nodejs.org/about/

So how to resolve the issue you have faced with. I can provide you with 2 ways:

  • using callbacks
  • using promises

Callbacks

That's actually what are you using at this moment. You need to run basic function and put there another (callback) function as additional argument, so once everything is ready callback function will be fired and you will be able to get results. How to receive results into your variable:

var searchQuery = {}; //or something specific like {name: 'Kitten Name'};
var foundKittens = [];
Kitten.find(searchQuery , function (err, kittens) {
    if (err) {
            //do something with error
    } else {
        foundKittens = kittens
    }
});

Please note that all the rest actions you have to proceed inside of existing callback due to specific of these async actions. Soon you will faced with the issue called 'Callback Hell'.

More about callback and 'Callback Hell' you may read there:

http://callbackhell.com/

Promises

That's more understandable and professional way of working with asynchronous functions. Mongoose ODM supports promises (http://mongoosejs.com/docs/api.html#promise_Promise), so you may do the following.

var searchQuery = {}; //or something specific like {name: 'Kitten Name'};
var foundKittens = [];

Kitten
  .find(searchQuery)
  .exec()
  .then(function(kittens){
      //here you can assign result value to your variable
      //but this action is useless as you are working with results directly
      foundKittens = kittens;
      return kittens;
  })
  .onReject(function(err){
      throw err; //or something else
  });

So then you just work inside of existing promise, you may have more and more 'then' statements like:

Kitten
  .find(searchQuery)
  .exec()
  .then(function(kittens){
      foundKittens = kittens;
      return kittens;
  })
  .then(countKittents)
  .then(changeSomethingInKittents)
  .then(saveKittentsToDb)
  .onReject(function(err){
      throw err; //or something else
  });

More about promises please read there:

http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

查看更多
登录 后发表回答