用Sails.js中的一个请求创build/更新多个logging

我想知道在一个请求中创build/更新多个logging的最佳做法是什么。 我知道我们可以使用Promise.all()来做到这一点。 但是如果我想告诉客户哪个logging成功了,哪个失败了呢?

例如,用户发布如下内容:

{ departmentId: 1, students: [ {name: 'John', studentId: 123}, {name: 'Mike', studentId: 124}, ] } 

而我目前的解决scheme是:

StudentController:

 var departmentId = req.param('departmentId'); var postStudents = req.param['students']; var department; var failedRecords = []; Department.findOne() .then(function (_department) { department = _department; var students = []; while (postStudents.length) { var student = postStudents.pop(); student.department = departmentId; var s = Student.create(s) .then(function(s){return s;}) .catch(function(e){ failedRecords.push(student)}); // A closure problem happens here students.push(s); } return students; }) .each(function (student) { department.students.add(student[0].id); return department.save().catch(function(e){/* log: add to department failed */}); }) .then(function () { return res.json({msg: "Success"}); }) .catch(function (e) { return res.json(404, {err: "Fail", records: failedRecords}); }); 

代码很丑,我也省略了代码来解决while循环中的闭包问题。 另外,我不知道如何保存到第二次catchReleaseRecords。

您应该能够简单地运行以下内容来为学生生成logging。 请参阅waterline-orm / models /创build更多。

 // create the students var students = [{name: 'John', studentId: 123},{name: 'Mike', studentId: 124}]; Student.create(students).exec(function createCB(err, created){ console.log('Created student with name ' + created[0].name); console.log('Created student with name ' + created[1].name); //Do other stuff here. }); 

我猜Sails使用Q库。 如果没有,您可以使用Q.()来将任何承诺转换为Q.()

所以,而不是Q.all()方法,你见过Q.allSettled()

这两个方法的区别( 从Q库指南 ):

全部函数返回一个值数组的承诺。 当这个承诺被履行时,这个数组包含原始承诺的履行价值,与承诺的顺序相同。 如果某个给定的承诺被拒绝,则返回的承诺立即被拒绝,而不是等待批处理的其余部分。 如果你想等待所有的承诺被履行或拒绝,你可以使用allSettled。

Q.allSettled()将等待所有的承诺完成,即使一个或多个被拒绝,并返回一个对象数组,如: { state: "fulfilled", value: v } or { state: "rejected", reason: r }

API参考 – promise.allSettled()

我不知道这是插入数据库的最佳做法,因为水线可能有批处理插入模式。 但是,我已经以这种方式发布到API来插入logging,并为我工作得很好。