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

时间:2015-03-31 12:20:17

标签: javascript asynchronous synchronization strongloop

我希望运行查找方法进行搜索,如果有人'放置'将我删除的类别ID分类为#39;类别'。但是find方法是异步的,我在执行过程中遇到错误......

my 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)

1 个答案:

答案 0 :(得分:0)

你不想在操作钩子中throw err,用下一个函数返回错误。

以下是我认为您想要做的事情:

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();
    });
 });
};