Slowdown due to non-parallel awaiting of promises in async generators

后端 未结 3 748
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 06:02

I\'m writing code using generators and Bluebird and I have the following:

var async = Promise.coroutine;
function Client(request){
    this.request = request         


        
3条回答
  •  春和景丽
    2020-11-27 06:52

    As it is mentioned in the Bluebird docs for Promise.coroutine, you need to watch out not to yield in a series.

    var county = yield countryService.countryFor(user.ip);
    var data = yield api.getCommentDataFor(user.id);
    var notBanned = yield authServer.authenticate(user.id);
    

    This code has 3 yield expressions, each of them stopping execution until the particular promise is settled. The code will create and execute each of the async tasks consecutively.

    To wait for multiple tasks in parallel, you should yield an array of promises. This will wait until all of them are settled, and then return an array of result values. Using ES6 destructuring assignments leads to concise code for that:

    Client.prototype.fetchCommentData = async(function* (user){
        var [county, data, notBanned] = yield [
    //             a single yield only: ^^^^^
            countryService.countryFor(user.ip),
            api.getCommentDataFor(user.id),
            authServer.authenticate(user.id)
        ];
        if (!notBanned)
            throw new AuthenticationError(user.id);
        return {
            country: country,
            comments: data,
            notBanned: true
        };
    });
    

提交回复
热议问题