如何将内部回调的结果传递到其父函数? [英] How to pass a result from inside callback out into its parent function?

查看:119
本文介绍了如何将内部回调的结果传递到其父函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Mongoose和MongoDB的MMEAN堆栈。我想测试集合Foo是否为空,但它涉及一个Mongoose find()函数与回调。 我不熟悉回调,因此我想知道如何从回调中获取一条信息到其父函数中。

I'm working with a MMEAN stack with Mongoose and MongoDB. I would like to test if the collection Foo is empty or not, but it involves a Mongoose find() function with a callback. I'm unfamiliar with callbacks, so I would like to know how to get a piece of information from inside a callback out into its parent function.

这是addFoo必须遵循的逻辑:
1.检查Foo集合是否为空
2.如果Foo为空,则保存新的Foo文档
3.如果Foo是不是空的,不保存新的Foo文档

This is the logic I must follow for addFoo: 1. check if the Foo collection is empty 2. If Foo is empty, save the new Foo document 3. If Foo is not empty, do not save the new Foo document

我调用保存方法 addFoo() from routes / index.js。

I'm calling the save method, addFoo(), from routes/index.js.

// routes/index.js
router.post('/foo', function(req, res, next){
  var foo = new Foo(req.body);
  foo.addFoo(function(err, bid){
    if(err){ return next(err); }
    res.json(foo);
  });
});

// models/Foo.js

var mongoose = require('mongoose');
var FooSchema = new mongoose.Schema({
  creator: String
});
mongoose.model('Foo', FooSchema);

FooSchema.methods.addFoo = function(cb){

  // finds all documents of Foo into the "results" array
  this.model("Foo").find(function(err, results){
    if (err){return err;}
    // if the Foo results array is empty
    if (results.length == 0){
      // HOW DO I LET addFOO() KNOW THAT THE ARRAY IS EMPTY?
      // somehow pass the boolean out to addFoo()
    }
  });

  // IF Empty
  // this.save(cb);

}


推荐答案

工作如下...

FooSchema.methods.addFoo = function(cb){
  var that = this;
  this.model("Foo").find(function(err, results){
    if (err){return err;}
    // if the Foo results array is empty
    if (results.length == 0){
      that.save(cb);
    }
  });
}

然而,如果你想根据你的实际需求将它传递给父级,你可以尝试如下....

However if you want to pass it to parent as per your actual requirement, then you can try it as below ....

 FooSchema.methods.addFoo = function(cb){
      var that = this;
      this.model("Foo").find(function(err, results){
        if (err){return err;}
        // if the Foo results array is empty

          that.commit(!results.length);//Calling a parent function from inside callback function

      });

       function commit(doCommit){
         if(doCommit) {  
            that.save(cb);
         }
       }
    }

这篇关于如何将内部回调的结果传递到其父函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆