如何组合来自不同JS文件的对Ajax数据库的多次调用

How to combine multiple call to Ajax Data base from different JS files

本文关键字:文件 Ajax 数据库 调用 JS 何组合 组合      更新时间:2023-09-26

我在一个进行Ajax调用的文件中有一些代码。此文件由每次创建新实例的多个其他文件作为函数调用。

这是正在调用的 JS 代码:

define(["underscore", "homeop", "domReady!"],
    function (_, homeop, domready) {
         
        var timeout = 500;
        return function (opUrl, opList, onCallback) {
            // IRRELEVANT CODE 
          
          var getFetch = function (optionName) {
                    $.ajax({
                        url: optionsUrl,
                        data: { optionNames: [optionName] }, 
                        type: "POST",
                        dataType: "json",
                        async: false,
                        traditional: true,
                        success: function (data) {
                            _.each(data, function (optionData, optionName) {
                                if (homeop.globalCache[optionName] === null) {
                                    homeop.globalCache[optionName] = optionData;
                                }
                            });
                            
                        },
                        error: function (message) {
                            console.error(message.responseText);
                        }
                    });
                };
          
          self.getInfo = function (optionName) {
            if (homeop.globalCache[optionName] === undefined) {
                    if (!_.contains(homeop.getOption(), optionName)) {
                        getFetch(optionName);
                    }
              // MORE IRRELEVANT CODE GOES HERE
          
          

在其他JS文件中,我调用get函数;例如

var these = new getOptions(optionsUrl, optionsList, onLoadCallback);
var getOpt = these.get(OptionsUrl);

问题是我多次调用从数据库中获取信息,导致多次调用我的 JS 文件。JS 文件的每个新实例都将创建一个 ajax 调用。

有没有办法等待所有调用完成,然后从数据库中获取数据?换句话说,我如何以某种方式将所有调用组合到我的"getOption.js"中?

谢谢

试试这个。您还可以实现队列代替堆栈

var optionStack = [];
var isAvailable = true;
var getFetch = function (optionName) {
  if(isAvailable){
      isAvilable = false; // function not available now
  }
  else {
    optionStack.push(optionName)
    return;
  }
  $.ajax({
    url: optionsUrl,
    data: { optionNames: [optionName] }, 
    type: "POST",
    dataType: "json",
    async: false,
    traditional: true,
    success: function (data) {
      _.each(data, function (optionData, optionName) {
        if (homeop.globalCache[optionName] === null) {
          homeop.globalCache[optionName] = optionData;
        }
      });
    },
    error: function (message) {
      console.error(message.responseText);
    },
    done: function (){
      isAvailable = true;
      if(optionStack.length > 0){
        getFetch(optionStack.pop());
      }
    }
  });
};