1

感谢@BenjaminGruenbaum,我有一个很好的promisified findOneAsync,但由于某种原因,ajax 在保存运行后没有运行该success函数..这只发生在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
  });

});
4

1 回答 1

2

在加入回调中,您返回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 ...
于 2014-07-23T00:10:17.147 回答