首页 > 解决方案 > 实现 javascript promise 的最佳实践

问题描述

大家好,我对 js 和异步编程很陌生。我使用 node.js 和 express 开始学习 js 服务器端和异步编程。我有实现回调承诺异步之类的问题。我曾经使用过回调,但我认为我的代码变得如此混乱且难以维护。现在我尝试在下面的代码中实现承诺。我的问题是:我使用承诺的方式有一个好的做法吗?因为我认为如果我像下面的代码那样实现“嵌套”承诺,与回调地狱相比没有什么不同。使用 Promise 的最佳实践是怎样的?谢谢

update_data_profil(req, res) {
        var nama_unit_org = req.body.nama_unit_org;
        var nama_ketua_unit_org = req.body.nama_ketua_unit_org;
        var nip_nim = req.body.nip_nim;
        var email = req.body.email;
        var no_hp = req.body.no_hp;
        var params;
        var user;
        if (helper.isExist(nama_unit_org) && helper.isExist(nama_ketua_unit_org) && helper.isExist(email)
            && helper.isExist(nip_nim) && helper.isExist(no_hp)) {
            if (nip_nim !== req.user.nip_nim) {
                params = {
                    nip_nim: nip_nim
                }
                user = new User_Model(params);
                user.getDataProfilByNIPorNIM()
                    .then(function (result) {
                        if (result) {
                            req.flash('message_err', "NIP/NIM telah dipakai akun lain.");
                            res.redirect('/manajemen_profil');
                        }
                        else {
                            params = {
                                id_user: req.user.id_user,
                                nip_nim: nip_nim,
                                nama_ketua_unit_org: nama_ketua_unit_org,
                                nama_unit_org: nama_unit_org,
                                email: email,
                                no_hp: no_hp,
                            };
                            user = new User_Model(params);
                            user.editDataProfil()
                                .then(function () {
                                    params = {
                                        session_id: req.sessionID
                                    };
                                    user = new User_Model(params);
                                    user.clearSession()
                                        .then(function () {
                                            req.flash('message_success', 'Edit data profil berhasil. Silahkan login untuk melanjutkan');
                                            res.render('index/login',
                                                {
                                                    message_success: req.flash('message_success')
                                                });
                                        }).catch(function (err) {
                                            req.flash('message_err', "Internal server error");
                                            res.redirect('/');
                                        });
                                })
                                .catch(function (err) {
                                    req.flash('message_err', "Internal server error.");
                                    res.redirect('/');
                                });
                        }

                    }).catch(function (err) {
                        req.flash('message_err', "Internal server error.");
                        res.redirect('/');
                    })
            }
            else {
                params = {
                    id_user: req.user.id_user,
                    nama_ketua_unit_org: nama_ketua_unit_org,
                    nama_unit_org: nama_unit_org,
                    email: email,
                    no_hp: no_hp
                };
                user = new User_Model(params);
                user.editDataProfil()
                    .then(function () {
                        req.flash('message_success', "Berhasil update profil.");
                        res.redirect('/manajemen_profil');
                    })
                    .catch(function (err) {
                        req.flash('message_err', "Internal server error");
                        res.redirect('/manajemen_profil');
                    });
            }
        }
        else {
            req.flash('message_err', "Tidak boleh ada field yang kosong!");
            res.redirect('/manajemen_profil');
        }
    }

标签: javascriptnode.js

解决方案


Nodejs Promise 最美丽的优点之一就是避免了回调地狱过程。有了承诺,如果你再次将一个嵌套在另一个里面,那么你就是在创造一个承诺地狱;)。

下面是使用 Promise 的更好方法之一。

链接:

 // Promises example using 'then'
user.getDataProfilByNIPorNIM().then(function(user) {
    ...
    return user.editDataProfil();
}).then(function(editDataProfilResults) {
    ....
    return user.clearSession();
}).then(function(clearSessionResult) {
   ....
   return
}).catch(function(err){
   .....
   process error
}) 

我遇到了下面的链接,它解释了 Promise 的用法。这可能会有所帮助。

https://www.joezimjs.com/javascript/javascript-asynchronous-architectures-events-vs-promises/


推荐阅读