簡體   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