我正在使用 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/