简体   繁体   English

在另一个函数JavaScript / JQuery中调用函数的最佳方法?

[英]Best way to call function inside of another function JavaScript/JQuery?

I have built function that checks if record exist in local storage, if not trigger ajax call to get the data. 我建立了一个功能来检查记录是否在本地存储中,如果不存在则触发ajax调用来获取数据。 Once data is returned I set the data in local storage. 返回数据后,我将数据设置在本地存储中。 After this function completes I have to pass the data to another function that will feed the data in the form. 此函数完成后,我必须将数据传递给另一个函数,该函数将以表格形式提供数据。 I'm wondering what is the best practice now days to achieve this? 我想知道如今实现这一目标的最佳做法是什么? I see more object oriented JavaScript now days and I'm wondering if any of OOP methods can be applied in this case. 现在,我看到了更多的面向对象的JavaScript,我想知道在这种情况下是否可以应用任何OOP方法。 Here is example of my fucntion: 这是我的功能示例:

function getData(fnName,storageID,recID){
    var inStorage = localStorage.hasOwnProperty(storageID) ? true  : false,
        frmData;

    if(inStorage) {
        frmData = JSON.parse(localStorage.getItem(storageID));
    }else{
        $.ajax({
            type: 'POST',
            url: 'AjaxFunctions.cfc?method='+fnName,
            data: {'recID':recID},
            dataType: 'json',
            async: false
        }).done(function(obj){
            if(obj.STATUS == "200"){
                var storageData = $.isEmptyObject(obj.DATA) ? null : JSON.stringify(obj.DATA);
                localStorage.setItem(storageID,storageData);
                frmData = storageData;
            }else{
                $('#error').html(obj.MESSAGE);
            }
        }).fail(function(jqXHR, textStatus, errorThrown){
            alert("Error: "+errorThrown);
        });
    }
    //frmFeed(frmData);
    return frmData;
}

Function above once completed should pass the data in another function that will populate the form: 上面的函数一旦完成,应该将数据传递到另一个将填充表格的函数中:

function frmFeed(frmData){
    //Loop over frmData and populate the fields
}

I know the one way to accomplish this is to simply call frmFeed inside getData function that I showed above (commented code). 我知道完成此操作的一种方法是在上面显示的getData函数(注释代码)中简单地调用frmFeed is there any other way to call frmFeed and pass the data? 还有其他方法可以调用frmFeed并传递数据吗? If anyone can provide some example please let me know. 如果有人可以提供一些示例,请告诉我。 Thank you! 谢谢!

There are several ways: 有几种方法:

  1. Callbacks 回调
  2. Promises 承诺

Not recommended would be to use synchronous ajax requests because it will block the UI. 不建议使用同步ajax请求,因为它将阻塞UI。

Here's an implementation using promises: 这是一个使用promises的实现:

function getData(fnName,storageID,recID){
    return new Promise(function(resolve, reject) {
      var inStorage = localStorage.hasOwnProperty(storageID) ? true  : false;

      if (inStorage) {
          resolve(JSON.parse(localStorage.getItem(storageID)));
      } else {
          $.ajax({
              type: 'POST',
              url: 'AjaxFunctions.cfc?method='+fnName,
              data: { 'recID': recID },
              dataType: 'json'
              // removed sync
          }).done(function(obj){
              if(obj.STATUS == "200"){
                  var storageData = $.isEmptyObject(obj.DATA) ? null : JSON.stringify(obj.DATA);
                  localStorage.setItem(storageID,storageData);
                  resolve(storageData);
              }else{
                  $('#error').html(obj.MESSAGE);
                  // or reject here
                  reject(obj);
              }
          }).fail(function(jqXHR, textStatus, errorThrown){
              alert("Error: "+errorThrown);
              // or reject may be better here
              reject({ 'jqXHR': jqXHR, 'textStatus': textSTatus, 'errorThrown': errorThrown });
          });
      }
    });
}

getData('blah', 'storageId', 'recId')
    .then(function(frmData) {
       frmFeed(frmData);
    });

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

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