首页 文章

从Jquery发布请求切换到现代Promise

提问于
浏览
0

我正在开发一个后端使用Flask Python的Web应用程序项目,以及前端的Javascript . 我想利用一些更现代的(ES6 / 7)风格的东西,比如Promises .

我一次向服务器发出单个Ajax请求 . 我一直在使用 $.post.done() 以及 .fail() 专门编写我的Ajax请求,我知道这些请求已经基于承诺或类似承诺 . 我的大部分代码都是风格的

  • 做功能设置和检查

  • 制作单个ajax请求

  • 成功

  • 状态良好,运行几个成功的代码位

  • 状态不佳,运行失败代码

  • 失败 - 运行失败代码

我似乎总是要考虑服务器失败的情况下服务器成功的情况,但它返回了错误的东西,我通常用 status 参数控制 . 我一直在用 then, catch, resolve, reject 查看直接 Promise 语法,我有一些问题 .

  • 根据我的简单Ajax请求,从我目前的格式切换到这种格式有什么好处吗?

  • 它可以用来简化我当前编写请求和处理故障情况的方式吗?

这是一个简单的登录示例,其中包含一个在单击登录按钮时调用的函数 .

$('#loginsubmit').on('click', this, this.login);

    // Login function
    login() {
        const form = $('#loginform').serialize();

      $.post(Flask.url_for('index_page.login'), form, 'json')
          .done((data)=>{
              if (data.result.status < 0) {
                  // bad submit
                  this.resetLogin();
              } else {
                  // good submit
                  if (data.result.message !== ''){
                      const stat = (data.result.status === 0) ? 'danger' : 'success';
                      const htmlstr = `<div class='alert alert-${stat}' role='alert'><h4>${data.result.message}</h4></div>`;
                      $('#loginmessage').html(htmlstr);
                  }
                  if (data.result.status === 1){
                      location.reload(true);
                  }

              }
          })
          .fail((data)=>{ alert('Bad login attempt'); });
    }

我有一个典型的更复杂的例子 . 在这种情况下,当打开和关闭按钮时,会初始化一些交互式元素 .

this.togglediv.on('change', this, this.initDynamic);   

    // Initialize the Dynamic Interaction upon toggle - makes loading an AJAX request
    initDynamic(event) {

        let _this = event.data;

        if (!_this.togglediv.prop('checked')){
            // Turning Off
            _this.toggleOff();
        } else {
            // Turning On
            _this.toggleOn();

            // check for empty divs
            let specempty = _this.graphdiv.is(':empty');
            let imageempty = _this.imagediv.is(':empty');
            let mapempty = _this.mapdiv.is(':empty');

            // send the request if the dynamic divs are empty
            if (imageempty) {
                // make the form
                let keys = ['plateifu', 'toggleon'];
                let form = m.utils.buildForm(keys, _this.plateifu, _this.toggleon);
                _this.toggleload.show();

                $.post(Flask.url_for('galaxy_page.initdynamic'), form, 'json')
                    .done(function(data) {
                        let image = data.result.image;
                        let spaxel = data.result.spectra;
                        let spectitle = data.result.specmsg;
                        let maps = data.result.maps;
                        let mapmsg = data.result.mapmsg;

                        // Load the Image
                        _this.initOpenLayers(image);
                        _this.toggleload.hide();

                        // Try to load the spaxel
                        if (data.result.specstatus !== -1) {
                            _this.loadSpaxel(spaxel, spectitle);
                        } else {
                            _this.updateSpecMsg(`Error: ${spectitle}`, data.result.specstatus);
                        }

                        // Try to load the Maps
                        if (data.result.mapstatus !== -1) {
                            _this.initHeatmap(maps);
                        } else {
                            _this.updateMapMsg(`Error: ${mapmsg}`, data.result.mapstatus);
                        }

                    })
                    .fail(function(data) {
                        _this.updateSpecMsg(`Error: ${data.result.specmsg}`, data.result.specstatus);
                        _this.updateMapMsg(`Error: ${data.result.mapmsg}`, data.result.mapstatus);
                        _this.toggleload.hide();
                    });
            }
        }
    }

我知道这已经大致使用了promises,但是我可以通过切换到 Promise then catch 语法来改进我的代码流吗?正如您所看到的,我最终会为真正的失败和成功的失败重复大量的失败案例代码 . 我的大多数代码看起来像这样,但我喜欢这样的.2507805

promise_ajax_call
  .then(do real success)
  .catch(all failure cases)

1 回答

  • 1

    我总是使用Bluebird Promises . 他们有一个Promise.resolve函数,你可以使用ajax . 关于Promises的一件事,如果 then 中的错误 throw ,它将被链接 catch . 一种清理它的方法可能是这样的(记住,这是伪的)

    Promise.resolve($.ajax(...some properties..))
        .then((data)=>{
            if(data.result.status < 0){
                //throw some error
            }
    
            // process the data how you need it
        })
        .catch((error){
            // either the ajax failed, or you threw an error in your then. either way, it will end up in this catch
        });
    

相关问题