promisified mongoose / mongodb保存不成功的Ajax调用?

我有一个伟大的promisified findOneAsync感谢@BenjaminGruenbaum ,但由于某种原因,阿贾克斯没有运行保存运行后的successfunction..这只发生promisified代码。

下面是运行成功函数refreshStories的ajax:

 console.log('there is a story: ' + AjaxPostData.story); // make an ajax call $.ajax({ dataType: 'json', data: AjaxPostData, type: 'post', url: liveURL + "/api/v1/stories", success: refreshStories, error: foundError }); 

这里是承诺的API调用:

 router.route('/stories') // create a story (accessed at POST http://localhost:4200/api/v1/stories) .post(function(req, res) { var story = new Models.Story(); var toArray = req.body.to; // [ 'user1', 'user2', 'user3' ] var to = Promise.map(toArray,function(element){ return Promise.props({ // resolves all properties user : Models.User.findOneAsync({username: element}), username : element, // push the toArray element view : { inbox: true, outbox: element == res.locals.user.username, archive: false }, updated : req.body.nowDatetime }); }); var from = Promise.map(toArray,function(element){ // can be a normal map return Promise.props({ user : res.locals._id, username : res.locals.username, view : { inbox: element == res.locals.user.username, outbox: true, archive: archive, }, updated : req.body.nowDatetime }); }); Promise.join(to, from, function(to, from){ story.to = to; story.from = from; story.title = req.body.title; return story.save(); }).then(function(){ console.log("Success! Story saved!"); }).catch(Promise.OperationalError, function(e){ console.error("unable to save findOne, because: ", e.message); console.log(e); res.send(e); throw err; // handle error in Mongoose save findOne etc, res.send(...) }).catch(function(err){ console.log(err); res.send(err); throw err; // this optionally marks the chain as yet to be handled // this is most likely a 500 error, while the top OperationError is probably a 4XX }); }); 

在连接callback中,您返回story.save() 。 这不是一个承诺。

你可能想要做的是这样的:

 var saveFunc = Promise.promisify(story.save, story); return saveFunc(); 

这将会提示save()方法。 你也可以Promise.promisifyAll(story)return story.saveAsync()

所以你的代码会变成:

 Promise.join(to, from, function(to, from){ story.to = to; story.from = from; story.title = req.body.title; var saveFunc = Promise.promisify(story.save, story); return saveFunc(); }).then(function(saved) { console.log("Sending response."); res.json(saved); }).catch ...