繁体   English   中英

异步功能不适用于Await

[英]Async function does not work with Await

我进行了以下设置,其中main()函数进行AJAX调用,并在SUCCESS内部调用getValue1()getValue2() 我正在学习如何使用关键字asyncawait

根据此SO帖子和此开发人员手册 ,以下代码应该起作用。 但是,事实并非如此。 有人可以告诉我为什么吗?

async function main() {
  $.ajax({
      url: "...", 
      success: function (object) {
          var html = '';
          for (var i = 0; i < object.length; i++) {
              var value1 = await getValue1(object[i].value1);
              html += '<p>' + value1 + '</p>';

              var value2 = await getValue2(object[i].value2);
              html += '<p>' + value2 + '</p>';

              console.log(html);
          }
      }
  });
}

function getValue1(value1) {
  $.ajax({
      url: "...", 
      success: function (value1) {
          return value1;
      } 
  });
}

function getValue2(value2) {
  $.ajax({
      url: "...", 
      success: function (value2) {
          return value2;
      } 
  });
}

首先,您需要将async关键字放在await所在的函数中。 为此,您需要在getValue1/2函数中返回Promise

下面的代码应该可以正常工作,但请注意:

  1. 所有请求都使用Promise.all同时处理,因此当它们全部解决后,它将结果记录在控制台中
  2. 我使用letconst关键字,因为我假设您使用的是JavaScript的最新版本

您可能需要看一下Promise的文档才能完全理解下面的代码。

function main() {
  $.ajax({
    url: 'https://api.ipify.org',
    success: function (object) {
      // this is for demonstration only:
      object = [
        {
          value1: 'https://api.ipify.org',
          value2: 'https://api.ipify.org',
        },
        {
          value1: 'https://api.ipify.org',
          value2: 'https://api.ipify.org',
        },
      ];
      // ^^^ remove this for your use

      // for some reasons, async callback in success won't work with jQuery
      // but using this self-calling async function will do the job
      (async function () {
        const requests = [];
        for (let i = 0; i < object.length; i++) {
          requests.push(getValue1(object[i].value1));
          requests.push(getValue2(object[i].value2));
        }

        // all requests are done simultaneously
        const results = await Promise.all(requests);

        // will print ["<your ip>", "<your ip>", ...]
        console.log(results);
      })();
    },
  });
}

function getValue1(param1) {
  // return a promise that resolve when request is done
  return new Promise(function (resolve, reject) {
    $.ajax({
      url: param1,
      success: resolve,
      error: reject,
    });
  });
}

function getValue2(param2) {
  // return a promise that resolve when request is done
  return new Promise(function (resolve, reject) {
    $.ajax({
      url: param2,
      success: resolve,
      error: reject,
    });
  });
}

// call main for testing
main();

暂无
暂无

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

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