我有great promisified findOneAsync thanks to @BenjaminGruenbaum,但由于某种原因,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
});
});
答案 0 :(得分: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 ...