2015-03-31 25 views
1

我想運行find方法搜索任何'place'是否有我刪除的'category'的categoryId。但find方法是異步,我在執行過程中有一個錯誤...strongloop script.js在運行前查找delete方法:如何同步運行異步方法?

我的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) 

回答

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