我已经将我的代码重组为承诺,并构建了一个由多个回调组成的精彩长扁平承诺链.then().最后我想返回一些复合值,并且需要访问多个中间承诺结果.但是,序列中间的分辨率值不在最后一个回调的范围内,我该如何访问它们?
function getExample() {
return promiseA(…).then(function(resultA) {
// Some processing
return promiseB(…);
}).then(function(resultB) {
// More processing
return // How do I gain access to resultA here?
});
}
Run Code Online (Sandbox Code Playgroud) 我正在使用直接的ES6 Promises(使用es6-promise polyfill库),我遇到了一个问题,即访问以前在链接中的承诺的结果.
这个问题在Angular/Q的背景下是相同的,但是我对答案不满意,并想看看是否有更好的方法:
请考虑以下代码段:
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?
});
Run Code Online (Sandbox Code Playgroud)
在链式承诺中,我想使用student我在第一个承诺中得到的对象.但正如所写,这无法访问它.我有几个明显的选择:
我实际上不知道这是如何工作的,但另一个问题中的解决方案表明我可以调用then结果HelpRequest.findByStudent()和调用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 …Run Code Online (Sandbox Code Playgroud)