gpt4 book ai didi

ajax - promisified mongoose/mongodb save 没有返回成功给ajax 调用?

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:22 25 4
gpt4 key购买 nike

我有一个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
});

这是具有 promise 的 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
});

});

最佳答案

在连接回调中,您返回story.save()。这不是一个 promise 。

您可能想做的是:

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

这将 promise save() 方法。您还可以Promise.promisifyAll(story)返回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 ...

关于ajax - promisified mongoose/mongodb save 没有返回成功给ajax 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24899776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com