简体   繁体   English

Node JS蓝鸟承诺

[英]Node JS bluebird promises

I am creating promises with node JS. 我正在用节点JS创建Promise。 But i have the idea that i still have a callback hell going on... 但是我有一个想法,我仍然有一个回调地狱...

That is because i need results from my first callback, in the third callback. 那是因为我需要第一个回调的结果,在第三个回调中。

I already tried it with bluebird, but i have some confusion about this. 我已经尝试过使用bluebird,但是对此我有些困惑。

Can anyone give me some sample code how i can write this out nicely? 谁能给我一些示例代码,我如何才能很好地写出来呢? See the following example: https://gist.github.com/ermst4r/8b29bf8b63d74f639521e04c4481dabb 请参见以下示例: https : //gist.github.com/ermst4r/8b29bf8b63d74f639521e04c4481dabb

Use async / await to avoid nested promises. 使用async / await避免嵌套的承诺。

You could refactor your code to something like this 您可以将代码重构为这样的内容

async function doSomething(){
    try {
        const user = await UserProfileMatch.getNewUser(item.fk_user_id)
        await ActiveAuctionProfile.closeActiveAuctionProfile(item.aap_id)

        if(user.length  > 0 ) {
            const is_active = await ActiveAuctionProfile.isProfileActive(user[0].profile_id)

            const number_of_profiles = await = UserProfileMatch.countActiveProfilesForUser(item.fk_user_id)

            if(is_active.result === 0 && number_of_profiles < config.settings.lovingbids_start_profile) {

                await UserProfileMatch.updateProfileMatch(item.fk_user_id, user[0].profile_id,1,false)

                await ActiveAuctionProfile.createNewActiveProfile({
                    fk_auction_profile_id:user[0].profile_id,
                    start_date:moment().format("YYYY-MM-DD HH:mm:ss") ,
                    expire_date:moment().add(config.settings.increment_settings,'seconds').format("YYYY-MM-DD HH:mm:ss")
                })

                ExpireProfileRegister.removeExpireResult(item.id);
                page++;
                next();

            } else {
                console.log("exists");
                ExpireProfileRegister.removeExpireResult(item.id);
                page++;
                next();
            }

        } else {
            console.log("niet");
            page++;
            next();
        }

    }catch(err){
       console.log("One of the promises failed:", err)
    }
}

Note that we declare the wrapping function with async and that instead of nesting the callbacks, we use await to tell the async function to wait for this function to finish before running the next line of code. 请注意,我们使用async声明了包装函数,而不是嵌套回调,而是使用await告诉async函数在运行下一行代码之前等待该函数完成。

Also note that all the await functions are wrapped in a try / catch block to catch any errors. 还要注意,所有等待函数都包装在try / catch块中,以捕获任何错误。 This is instead of using the .catch() notation. 这不是使用.catch()表示法。

Read more about async functions here 在此处阅读有关异步功能的更多信息

I couldn't debug but something along these lines should give you a refactored code using promises correctly. 我无法调试,但是按照这些原则,应该可以正确使用promises为您提供重构的代码。

UserProfileMatch.getNewUser(item.fk_user_id)
                .then(user => ActiveAuctionProfile.closeActiveAuctionProfile(item.aap_id))
                .then(() => user.length  > 0 ? ActiveAuctionProfile.isProfileActive(user[0].profile_id)
                                             : (console.log("niet"), page++, next()))
                .then(is_active => [UserProfileMatch.countActiveProfilesForUser(item.fk_user_id), is_active.result])
                .then(([number_of_profiles,n]) => n === 0 &&
                                                  number_of_profiles < config.settings.lovingbids_start_profile ? UserProfileMatch.updateProfileMatch(item.fk_user_id, user[0].profile_id,1,false))
                                                                                                                : (console.log("exists"),
                                                                                                                   ExpireProfileRegister.removeExpireResult(item.id),
                                                                                                                   page++,
                                                                                                                   next());
                .then(() => ActiveAuctionProfile.createNewActiveProfile({ fk_auction_profile_id: user[0].profile_id,
                                                                          start_date           : moment().format("YYYY-MM-DD HH:mm:ss") ,
                                                                          expire_date          : moment().add(config.settings.increment_settings,'seconds').format("YYYY-MM-DD HH:mm:ss")
                                                                        })
                .then(() => (ExpireProfileRegister.removeExpireResult(item.id), page++, next()));

Please note that at the 3rd then stage i returned an array like 请注意,在第三届then阶段,我返回数组一样

[UserProfileMatch.countActiveProfilesForUser(item.fk_user_id), is_active.result]

which carries the is_active.result to the next then stage, at where we collect it as n through array destructuring. 携带is_active.result到下一个then的阶段,在那里我们收集它作为n通过阵列解构。

Nice thanks all for your feedback. 很好,谢谢大家的反馈。 I read about async and async.series seems to be the best way for me. 我读过asyncasync.series对我来说似乎是最好的方法。 It keeps my code structured. 它使我的代码保持结构化。 See .... 见....

                            var get_user;
                            var user_active;
                            var user_profile;
                            async.series([

                                // check for the new user
                                function checkForNewUser(callback)
                                {
                                    UserProfileMatch.getNewUser(item.fk_user_id).then(function (user) {
                                        get_user = user;
                                        callback(null,user);

                                    });
                                },
                                // close the profile
                                function closeProfile(callback)
                                {
                                    ActiveAuctionProfile.closeActiveAuctionProfile(item.aap_id).then(function () {
                                        if (get_user.length > 0) {
                                            ActiveAuctionProfile.isProfileActive(get_user[0].profile_id).then(function (is_active) {
                                                user_active = is_active.result;
                                                callback(null,user_active);
                                            });
                                        } else {
                                            callback(null,false);
                                        }

                                    });

                                },

                                // count the active profiles
                                function countActiveProfiles (callback) {

                                    UserProfileMatch.countActiveProfilesForUser(item.fk_user_id).then(function (number_of_profiles) {
                                        user_profile = number_of_profiles;
                                        callback(null,user_profile);
                                    });
                                },

                                // decide when we want to create an user
                                function determineCreation(callback) {

                                    if(user_active === 0 && user_active === 0) {
                                        UserProfileMatch.updateProfileMatch(item.fk_user_id, get_user[0].profile_id, 1, false).then(function () {
                                            ActiveAuctionProfile.createNewActiveProfile({
                                                fk_auction_profile_id: get_user[0].profile_id,
                                                start_date: moment().format("YYYY-MM-DD HH:mm:ss"),
                                                expire_date: moment().add(config.settings.increment_settings, 'seconds').format("YYYY-MM-DD HH:mm:ss")
                                            }).then(function () {
                                                ExpireProfileRegister.removeExpireResult(item.id);
                                                callback(null,true);
                                            });

                                        });
                                    } else {
                                        ExpireProfileRegister.removeExpireResult(item.id);
                                        callback(null,true);
                                    }
                                }

                            ], function(err,res) {
                                // after done, go to the next page
                                page++;
                                next();
                            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM