仅在完全执行上一个函数后才执行Javascript函数[重复]

问题描述 投票:-2回答:2

我有2个函数,doFirst()和doSomethingElse()。现在,第一个功能包括大约10个AJAX请求,这些条件在检查是否选择了该过滤器的条件下执行。这些AJAX请求正在与URL进行通信,并在各自的数组中保存一组ID。完成此操作后,必须启动doSomethingElse()才能绘制结果表。此时,我将通过设置超时来执行它们。我想知道一种更好的方法来等待函数完成,然后执行下一个函数。任何帮助是极大的赞赏。谢谢!

            //How I am currently calling the functions:

            doFirst();
            doSomethingElse();



               function doFirst(){
                 var filterArrayTaxSel1 = $("#taxIA span").get().map(el => el.textContent);
                                for (var i = 0; i < filterArrayTaxSel1.length; i++) {
                                    filterArrayTaxSel1[i] = filterArrayTaxSel1[i].replace(" ", "%20");
                                }
                                // taxgroup2 - Selector
                                queryBuilder = filterArrayTaxSel1;
                                //console.log(queryBuilder);
                                console.log(filterArrayTaxSel1);
                                if (filterArrayTaxSel1.length > 0) {
                                    if (filterArrayTaxSel1.length > 0 && filterArrayTaxSel1[0] != "All") {
                                        console.log("I am inside the IF!");
                                        for (var i = 0; i < filterArrayTaxSel1.length; i++) {
                                            var baseURL = "some URL here";
                                            console.log(baseURL);
                                            responses(baseURL);
                                            function responses(baseURL) {
                                                $.ajax({
                                                    url: baseURL,
                                                    type: "get",
                                                    cache: false,
                                                    headers: {
                                                        'Content-Type': 'application/json'
                                                    },
                                                    success: function (data) {
                                                        console.log(data.features.length);
                                                        for (var i = 0; i < data.features.length; i++) {
                                                            if (taxArrayT1.indexOf(data.features[i].properties.taxon_id) == -1) {
                                                                taxArrayT1.push(data.features[i].properties.taxon_id);
                                                            }
                                                        }
                                                        console.log("In the Invertebrate Animals Section 1");
                                                        console.log(taxArrayT1.length);
                                                    }
                                                })
                                            }
                                        }
                                    }
                                    else if (filterArrayTaxSel1[0] == "All") {
                                        console.log("I am inside the IF!");
                                        var baseURL = "some URL here";
                                        console.log(baseURL);
                                        responses(baseURL);
                                        function responses(baseURL) {
                                            $.ajax({
                                                url: baseURL,
                                                type: "get",
                                                cache: false,
                                                headers: {
                                                    'Content-Type': 'application/json'
                                                },
                                                success: function (data) {
                                                    console.log("I am inside the ELSE IF ALLL!");
                                                    console.log(data.features.length);
                                                    for (var i = 0; i < data.features.length; i++) {
                                                        if (taxArrayT1.indexOf(data.features[i].properties.taxon_id) == -1) {
                                                            taxArrayT1.push(data.features[i].properties.taxon_id);
                                                        }
                                                    }
                                                    console.log("In the Invertebrate Animals Section 2");
                                                    console.log(taxArrayT1.length);
                                                }
                                            })
                                        }
                                    }
                                    //Selection 1 Tax Group AJAX Call   Sensitivity ARRAY WITH 0 to Multiple CASES - ENDS.
                                }
     //some more AJAX Calls depending on whether the filter exists
        //End of function
                }



function doSomethingElse(){
//Code to draw the Table using the arrays from the previous function
}
javascript html ajax asynchronous
2个回答
1
投票

Promise只是一个对象,您可以将执行某些工作的某些函数传递给该对象,完成后它将调用一个回调函数-用于后续操作。

您可以在以下位置找到完整的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype

例如,您有一个返回Promise对象的函数:

function makeAjaxCall(url, methodType){
   var promiseObj = new Promise(function(resolve, reject){
      var xhr = new XMLHttpRequest();
      xhr.open(methodType, url, true);
      xhr.send();
      xhr.onreadystatechange = function(){
      if (xhr.readyState === 4){
         if (xhr.status === 200){
            console.log("xhr done successfully");
            var resp = xhr.responseText;
            var respJson = JSON.parse(resp);
            resolve(respJson);
         } else {
            reject(xhr.status);
            console.log("xhr failed");
         }
      } else {
         console.log("xhr processing going on");
      }
   }
   console.log("request sent succesfully");
 });
 return promiseObj;
}

然后您进行多个ajax调用:

let promise1 = makeAjaxCall(URL1, "GET");
let promise2 = makeAjaxCall(URL2, "GET");
let promise3 = makeAjaxCall(URL2, "GET");

然后您有一个“监听器”,它等待所有诺言(ajax调用)完成:

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});

您有很多关于该主题的文章和文档:


0
投票

Promise对象代表最终的完成(或失败)异步操作及其结果值。

这里是一个示例,说明如何使用Promise对象使异步代码(例如AJAX请求)更易于处理。 Promise似乎是解决您的问题的理想人选。您可以执行以下操作:


-1
投票

在您的代码中,您正在使用jQuery,因此您可以利用其一些内置方法。您基本上希望跟踪阵列中的所有Ajax调用,因此当您进行Ajax调用时,请将它们推入阵列中。当它们全部完成后,您可以使用jQuery的Promise.all执行下一步。

基本思路:

const doFirst = () => {
  console.log('Making AJAX requests, please wait..');
  const asyncActions = [
    //Wrap all your async code in a Promise
    new Promise((resolve, reject) => {
      //Resolve some phony data as part of our AJAX request simulation
      setTimeout(() => resolve({
        name: 'Item 1',
        id: 1
      }), 1000)
    }),
    new Promise((resolve, reject) => {
      setTimeout(() => resolve({
        name: 'Item 2',
        id: 2
      }), 4000)
    }),
    Promise.resolve({
      name: 'Item 3',
      id: 3
    })
  ];

  //Since all your async actions are stored in a iterable, we can use
  return Promise.all(asyncActions);
}

const doSomethingElse = values => {
  console.log('Here is the data returned from our AJAX requests:');
  values.forEach(value => {
    console.log(`Name: ${value.name} || ID: ${value.id}`)
  });
}

doFirst().then(doSomethingElse);

-1
投票

此问题已在$.when()处得到了更详细的解答,您可能想检查一下。

© www.soinside.com 2019 - 2024. All rights reserved.