当一个承诺依赖于另一个时,Bluebird的Promise.all()方法 [英] Bluebird's Promise.all() method when one promise is dependent on another

查看:55
本文介绍了当一个承诺依赖于另一个时,Bluebird的Promise.all()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些当前看起来像这样的代码,因为我的代码中有依赖项.我想知道是否有更干净的方法可以通过Promise.all()做到​​这一点?这是我的伪代码:

I'm writing some code that currently looks like this because I have dependencies in my code. I was wondering if there was a cleaner way to do this with Promise.all()? Here is my pseudo code:

        return someService.getUsername()
            .then(function(username) {
                user = username;
            })
            .then(function() {
                return someService.getUserProps(user);
            })
            .then(function(userProps) {
                userProperties = userProps;
                return someService.getUserFriends(user);
            })
            .then(function(userFriends) {
                friends = userFriends;
            })
            .catch(error)
            .finally(function(){
                // do stuff with results
            });

重要的是,我需要用户才能对getUserProps()和getUserFriends()进行后两个调用.我以为可以这样使用Promise.all():

The important thing is that I need user before I can make the second two calls for getUserProps() and getUserFriends(). I thought I could use Promise.all() for this like so:

var user = someService.getUsername()
    .then(function(username) {
        user = username;
    })
var getUserProps = someService.getUserProps(user);
var getUserProps = someService.getUserFriends(user);

return Promise.all(user, getUserProps, getUserFriends, function(user, props, friends) {
    // do stuff with results
})

但是我无法使它正常工作.这是使用.all的正确案例吗?

But I cannot get this to work. Is this the correct case to use .all?

推荐答案

Promise.all()设计用于并行操作,在该操作中,您启动了一堆异步操作以同时运行,然后告诉您它们何时全部完成.

Promise.all() is designed for parallel operation where you launch a bunch of async operations to run at the same time and then it tells you when they are all done.

它不会以任何方式将一个序列与另一个序列的完成进行比较.因此,您不能使用它来等待用户准备就绪,然后让其他操作使用该用户.只是不是为了做到这一点.

It does not sequence one versus the completion of another in any way. So, you can't use it to wait for the user to be ready and then have the other operations use that user. It just isn't designed to do that.

您可以先获得用户,然后再完成该操作,您可以将Promise.all()与其他两项操作一起使用,我认为这两项操作可以同时运行,并且彼此之间不依赖.

You could get the user first and then when that is complete, you could use Promise.all() with your other two operations which I think can be run at the same time and don't depend upon each other.

var user;
someService.getUsername().then(function(username) {
    user = username;
    return Promise.all(getUserProps(user), getUserFriends(user));
}).then(function() {
    // do stuff with results array
}).catch(function() {
    // handle errors
});

这篇关于当一个承诺依赖于另一个时,Bluebird的Promise.all()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆