strongloop script.js 运行 在删除方法之前找到:如何 运行 同步异步方法?

strongloop script.js run find in before delete method: how run async method in sync?

如果有人 'place' 有我删除的 'categorie' 的类别 ID,我想 运行 找到搜索方法。但是查找方法是异步的,我在执行过程中出错...

我的script.js:

module.exports = function(app){

 var categorie = app.models.categorie;
 var place = app.models.place;

 categorie.observe("before delete", function(ctx, next){
    place.find({ "categoryId": ctx.where.id },function(err, models){
        if(err){
            throw err;
        }
        if(models.length > 0){
            console.log("places avec categoryId");
            throw new Error('Impossible de supprimer, place(s) liée(s)');
        }
    });

    next();
 });
};

和错误:

places avec categoryId

events.js:72
    throw er; // Unhandled 'error' event
          ^
Error: Impossible de supprimer, place(s) liée(s)
at /home/pitt/myapp/server/boot/script.js:20:23
at Object.forward (/usr/lib/node_modules/strongloop/node_modules/strong-agent/lib/proxy.js:79:23)
at eval (eval at wrap (/usr/lib/node_modules/strongloop/node_modules/strong-agent/lib/proxy.js:193:20), <anonymous>:3:21)
at allCb (/home/pitt/myapp/node_modules/loopback-datasource-juggler/lib/dao.js:1232:7)
at /home/pitt/myapp/node_modules/loopback-connector-mongodb/lib/mongodb.js:597:7
at handleCallback (/home/pitt/myapp/node_modules/loopback-connector-mongodb/node_modules/mongodb/lib/utils.js:95:12)
at /home/pitt/myapp/node_modules/loopback-connector-mongodb/node_modules/mongodb/lib/cursor.js:571:16
at handleCallback (/home/pitt/myapp/node_modules/loopback-connector-mongodb/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:234:5)
at setCursorDeadAndNotified (/home/pitt/myapp/node_modules/loopback-connector-mongodb/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:424:3)
at Cursor.next (/home/pitt/myapp/node_modules/loopback-connector-mongodb/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:585:7)

你不想throw err在运行hooks时,return错误与下一个函数。

这是我认为你想要做的事情:

module.exports = function(app){

 var categorie = app.models.categorie;
 var place = app.models.place;

 categorie.observe("before delete", function(ctx, next){
    place.find({ "categoryId": ctx.where.id },function(err, models){
        if(err){
            // pass error which will cancel the delete operation
            // i'm using return to stop execution as well
            return next(err);
        }
        if(models.length > 0){
            console.log("places avec categoryId");
            // you can also create your own new errors, just pass them to next as well
            return next(new Error('Impossible de supprimer, place(s) liée(s)'));
        }
        // because the find is async you need your next here, within the callback function so the earlier function knows to wait until this point.
        next();
    });
 });
};