【问题标题】:Await multiple ajax calls inside function?等待函数内的多个ajax调用?
【发布时间】:2020-08-23 05:12:50
【问题描述】:

上下文:制作一个 ajax 繁重的页面,根据先前选择器选择的内容更改不同选择器中的值。正在根据之前的条目制作“重新填充”选项。

When selector 1 is changed, an ajax call is made that populates both selector 2 and 3. Selector 1's options never change.


当您从先前的条目“重新填充”时,代码首先更改选择器 1 的值,然后激活选择器 1 上的更改事件。

function repopulateFromEntry(event)  {
    // We want the children of the parent TR.
    // <tr>
    //  <td>...</td>
    //  ...
    //  <td><button></td>
    // <tr>
    let td_list = event.target.parentElement.parentElement.children;

    $('#selector1').val(td_list[0].innerHTML);
    $('#selector1').change();
    // Do other things that rely on prior to be finished
    // Problem is here.
};

选择器 1 的更改事件如下所示。

async function executeAjax(url, success) {
    return await $.ajax({
        url: url,
        type: "GET",
        success: success
    });
}

$('#selector1').change(async function(e) {
    await executeAjax('api/selector2' + $("#selector1").val(), function() {
        // Set selector2 from ajax data
    });
    await executeAjax('api/selector3' + $("#selector1").val(), function() {
        // Set selector3 from ajax data
    });
});

根据 selector1 的值设置选择器选项后,它会进入并为选择器 2 和 3 选择正确的值。


我的问题是选择器 2 和 3 的值的重新选择在选项完全填充到选择器之前被调用,导致重新选择失败。

我显然在 async/await/ajax 部分中遗漏了一些东西,以防止它在没有完成两个调用的情况下继续,但我似乎看不出我的问题是什么。

【问题讨论】:

  • 您应该从executeAjax 函数中删除回调参数。改用承诺链!
  • 重新选择选择器 2 和 3 的值” - 代码在哪里?

标签: javascript jquery ajax async-await


【解决方案1】:

好的,所以我使用 async/await 进行 $.ajax 调用,然后在您的更改事件处理程序中,我使用 .then 方法对结果数据进行操作。 (也可以在事件处理程序中使用 async await,但是由于您最初拥有它并且它不起作用,因此我选择了 Promise)。

我很确定这应该可以,但如果不行,请告诉我控制台显示的内容。

注意在设置每个选择器的值之前,您可能需要 console.log 结果并提取您要查找的数据。您可以在 .then 方法中执行此操作。

async function executeAjax(url) {

    let result;

    try { 
        result = await $.ajax({
            url: url,
            type: "GET"
        });

        return result;

    } catch (error) {
        console.log(error);
    }
}

$('#selector1').change(function(e) {

    executeAjax('api/selector2' + $("#selector1").val())
    .then((result) => { 
        // console.log(result);  <-- may need to find and pull the data you are looking for out of result
        // let myVal = result[?]['something'].orother;
        $("#selector2").val(result); 
    });

    executeAjax('api/selector3' + $("#selector1").val())
    .then((result) => {
        // console.log(result);  <-- may need to find and pull the data you are looking for out of result
        // let myVal = result[?]['something'].orother;
        $("#selector3").val(result);
    });

});

【讨论】:

  • 同样的事情发生了。在 ajax 完成填充选择器 2 和 3 之前,它会尝试进一步执行代码。
  • @NicholasSteichen 好的,我更新了答案,这应该可以。
  • 我实际上是在你修复它之前想出的 - 仍然标记为正确的值。感谢您的帮助!
  • @NicholasSteichen 很高兴你成功了。干杯!
猜你喜欢
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 2012-07-19
  • 2015-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多