javascript – 承诺链接:使用前一个承诺的结果然后回调

参见英文答案 > How do I access previous promise results in a .then() chain?                                    15个
我正在使用直接的ES6 Promises(使用es6-promise polyfill库),我遇到了一个问题,即访问以前在链接中的承诺的结果.

这个问题在Angular / Q的背景下是相同的,但是我对答案不满意,并想看看是否有更好的方法:

How to access result from the previous promise in AngularJS promise chain?

请考虑以下代码段:

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?
});

在链式承诺中,我想使用我在第一个承诺中获得的学生对象.但正如所写,这无法访问它.我有几个明显的选择:

>将学生存放在外部范围内的变量中(yuck)
>我实际上不知道这是如何工作的,但是另一个问题中的解决方案建议我可以调用HelpRequest.findByStudent()和Promise.resolve的结果,然后调用Student.find()中的组合结果.然后调用.不过,我认为以下实现不起作用.

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
});

我绝对不希望嵌套在Student.find()方法中的helpRequest的处理,因为这违背了链接Promises的目的;即使第二个例子可以工作到一个可用的状态,它仍然感觉像一个黑客.

有没有更好的方法来实现这一点,而无需引入全局状态或嵌套到我的代码中?例如,有没有办法在多个值上调用Promise.resolve(),其中一些可能是promises而另一些则不是?

我很好奇,希望我有替代方案/能够理解如何在不引入嵌套或状态的情况下使其正常工作!

解决方法:

在我看来,承诺的禅就是要弄清楚它们实际上只是异步价值.如果您开始使用它们,这些问题在许多情况下会变得更简单.它不是一颗银弹,但肯定会有所帮助:

在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
});

在另一个更丰富的诺言库(蓝鸟):

var student = Student.find();
var helpRequest = student.then(HelpRequest.findByStudent);
Promise.join(student, helpRequest, function(student, helpRequest){
    // access both here
});

相关文章

最后的控制台返回空数组.控制台在ids.map函数完成之前运行va...
我正在尝试将rxJava与我已经知道的内容联系起来,特别是来自J...
config.jsconstconfig={base_url_api:"https://douban....
我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不...
config.jsconstconfig={base_url_api:"https://douban....
这是我的代码main.cpp:#include<string>#include<...