我正在使用直接的 ES6 Promise(使用 es6-promise polyfill 库),并且在访问链接的 Promise 中的先前 Promise 的结果时遇到了问题。
这个问题在 Angular/Q 的上下文中是相同的,但我对答案不满意,想看看是否有更好的方法:
如何访问 AngularJS 承诺链中前一个承诺的结果?
考虑下面的代码片段:
Student.find().then(function(student) {
return HelpRequest.findByStudent(student);
}, function(error) { //... }
).then(function(helpRequest) {
// do things with helpRequest...
// PROBLEM: I still want access to student. How can I get access to it?
});
在连锁承诺中,我想使用student
我在第一个承诺中得到的对象。但正如所写,这无法访问它。我有几个明显的选择:
- 将学生存储在外部作用域的变量中(恶心)
-
我实际上不知道这是如何工作的,但另一个问题中的解决方案建议我可以打电话then
的结果HelpRequest.findByStudent()
and Promise.resolve
内的综合结果Student.find().then
称呼。不过,我认为下面的实现不会起作用。
Student.find().then(function(student) {
var data = {student: student};
HelpRequest.findByStudent(student).then(function(helpRequest) {
data.helpRequest = helpRequest;
});
// PROBLEM: if HelpRequest.findByStudent(student) is asynchronous, how
// does this get the data before returning?
return data;
}, function(error) { //... }
).then(function(helpRequest) {
// do things with helpRequest and student
});
我绝对不想做处理helpRequest
嵌套在里面Student.find()
方法,因为这违背了链接 Promise 的目的;即使第二个示例可以进入可用状态,它仍然感觉像是一个黑客。
有没有更好的方法来实现这一目标,而无需引入全局状态或嵌套到我的代码中?例如,有没有办法调用Promise.resolve()
关于多个值,其中一些可能是承诺,而另一些则不是?
我很好奇,希望我有替代方案/能够理解如何在不引入嵌套或状态的情况下使其正常工作!
在我看来,Promise 的禅宗就是弄清楚它们实际上只是异步值。如果您开始像这样使用它们,那么在许多情况下这些问题会变得更简单。这不是灵丹妙药,但确实有帮助:
In ES5:
var student = Student.find();
var helpRequest = student.then(HelpRequest.findByStudent);
Promise.all([student, helpRequest]).then(function(results){
var student = results[0];
var helpRequest = results[1];
// access both here
});
在 ES6 中,具有其所有功能:
var student = Student.find();
var helpRequest = student.then(HelpRequest.findByStudent);
Promise.all([student, helpRequest]).then(([student, helpRequest]) => {
// access both here
});
在另一个更丰富的承诺库(bluebird)中:
var student = Student.find();
var helpRequest = student.then(HelpRequest.findByStudent);
Promise.join(student, helpRequest, function(student, helpRequest){
// access both here
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)