2017-04-25 48 views
0

是他们在promise中转换的其他方式吗?bluebired promisify函数没有转换为承诺

var Promise = require("bluebird"); 
let findOneOrCreate = require('mongoose-find-one-or-create'); 
findOneOrCreate = Promise.promisify(findOneOrCreate); // not converted to promise 

我用像当年在。那么(): -

 db.employee.findOneOrCreate({ 
       organization: model.organization.id, 
       EmpDb_Emp_id: model.EmpDb_Emp_id 
      }, model) 
      .then((employee, created) => { 
       if (!created) { 
        throw 'employee already exist'; 
       } 
       return employee; 
      }).catch(err => { 
       throw err; 
      }); 

它给出了一个错误: -

无法读取的不确定

+1

'它给出一个错误' - 什么?你发布的代码? (不太可能,你不使用'.then') - 你确定你知道你在做什么吗? –

+1

'promisify'不返回承诺 - 它返回一个*函数*,当被调用时返回一个承诺。你在哪里打电话? – Bergi

+0

'mongoose-find-one-or-create'模块存在缺陷(比赛条件),您应该考虑使用内置的['findOneAndUpdate'](http://mongoosejs.com/docs/api.html#query_Query -findOneAndUpdate)与'upsert:true'相结合。这也意味着你不必提出任何提议,因为Mongoose支持[开箱即用]承诺(http://mongoosejs.com/docs/promises.html)。 – robertklep

回答

2

首先属性 '然后' ,根据bluebird documentation,

the node function should conform to node.js convention of accepting a callback as last argument

mongoose-find-one-or-create仅接受schema作为参数,并将此架构扩展为findOneOrCreate函数。所以看起来require('mongoose-find-one-or-create')不能被promisified。您可以尝试扩展架构的promisifying findOneOrCreate代替:

var findOneOrCreate = require('mongoose-find-one-or-create'); 
var PersonSchema = mongoose.Schema({...}); 
PersonSchema.plugin(findOneOrCreate); 
var Person = mongoose.model('Person', PersonSchema); 
var findOneOrCreatePromise = Promise.promisify(Person.findOneOrCreate); 

而且记住,Promise.promisify()返回一个函数,所以你需要调用then之前调用它:

findOneOrCreatePromise().then(...) 

不仅仅是

findOneOrCreatePromise.then(...) 
+0

它被转换为承诺,但它不能正常工作..我尝试回调功能它正在工作审计那里 – hardy