javascript - Node JS bluebird promise

标签 javascript node.js promise

我正在使用 Node JS 创建 Promise。但我有一个想法,我仍然有一个回调 hell 正在发生......

那是因为我需要在第三次回调中获得第一次回调的结果。

我已经用 bluebird 尝试过了,但我对此有些困惑。

谁能给我一些示例代码,我如何才能很好地写出这个代码? 请参见以下示例: https://gist.github.com/ermst4r/8b29bf8b63d74f639521e04c4481dabb

最佳答案

使用 async/await 来避免嵌套的 Promise。

您可以将代码重构为这样的内容

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

请注意,我们使用 async 声明了包装函数,并且我们没有嵌套回调,而是使用await 告诉异步函数在运行下一行代码之前等待该函数完成。

另请注意,所有await 函数都包含在try/catch block 中以捕获任何错误。这不是使用 .catch() 表示法。

了解有关异步函数的更多信息 here

关于javascript - Node JS bluebird promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49923487/

相关文章:

javascript - redux store 保存在哪里?

javascript - 使用canvas.js在单个页面中导出多个图表

javascript - 类型错误 : Object #<Object> has no method 'Schema'

javascript - 使用两个中间 $.getJSON 调用将字符串数组转换为对象数组

javascript - 如何用 Promises 实现流畅的接口(interface)?

javascript - 问题 - 在 Windows Mobile 6.1 - IE Mobile6 上使用 Javascript 将动态 HTML 设置为 iFrame

javascript - 我如何在 React 功能组件中生成 HTML?

node.js - 在nodejs中重定向未打开playstore

node.js - 在 selenium-webdriver.js 测试中获取测试标题和状态

javascript - 我想从mysql的connection.query中取出结果并将其保存在nodejs的全局作用域链中