简体   繁体   English

异步等待数组数据

[英]Async await on array data

For some reason my async call is not working as expected.由于某种原因,我的异步调用没有按预期工作。 Here's what I'm trying to do:这是我正在尝试做的事情:

  1. Make several ajax calls in a loop在循环中进行几个 ajax 调用
  2. On success, push some API data to a global array成功后,将一些 API 数据推送到全局数组
  3. Use that array in another function (eg print it out)在另一个 function 中使用该数组(例如打印出来)
var authcodes = ["E06000001","E06000002","E06000003"];
var dict = [];

async function ajaxCall() {
    for(var i=0;i<authcodes.length;i++){
        $.ajax({
           type: "GET",
           url: 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaCode=' + authcodes[i] +'&structure={"areaCode":"areaCode","cumCasesByPublishDate":"cumCasesByPublishDate"}',
            dataType: "json",
            success: function(data) {
                dict.push(data.data[0].cumCasesByPublishDate);
            }
       });

    } return dict;
}

async function printArr () {
    const someApiRes = await ajaxCall()
    console.log(someApiRes[1]); //this doesn't work
    console.log(dict[1]); //this doesn't work

}

printArr();

Here is the JSFiddle with code commented: https://jsfiddle.net/gjv9hrpo/1/这是带有注释代码的 JSFiddle: https://jsfiddle.net/gjv9hrpo/1/

I understand that the printArr() function has to be ran after the array is populated due to the async nature which I hoped the await would solve.我知道 printArr printArr() function 必须在阵列填充后运行,因为我希望等待能够解决的async性质。 Am I using it wrong?我用错了吗?

Thanks.谢谢。

Use promise.All()使用 promise.All()

async function ajaxCall() {
  var promises = [];
    for(var i=0;i<authcodes.length;i++){
        promises.push($.ajax({
           type: "GET",
           url: 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaCode=' + authcodes[i] +'&structure={"areaCode":"areaCode","cumCasesByPublishDate":"cumCasesByPublishDate"}',
            dataType: "json",
            success: function(data) {
                dict.push(data.data[0].cumCasesByPublishDate);
            }
       }));

    }
    await Promise.all(promises); 
    return dict;
}

It might make more sense to do this with promises.用 Promise 来做这件事可能更有意义。

Promise.all lets you know when either all input promises have fulfilled or when one of them rejects. Promise.all让您知道所有输入承诺何时已履行或其中一个承诺何时拒绝。

 var authcodes = ["E06000001", "E06000002", "E06000003"]; function ajaxCalls() { return Promise.all( authcodes.map((code) => { return new Promise(async (resolve) => { const response = await fetch( `https://api.coronavirus.data.gov.uk/v1/data?filters=areaCode=${code}&structure={"areaCode":"areaCode","cumCasesByPublishDate":"cumCasesByPublishDate"}` ) const json = await response.json(); resolve(json.data[0].cumCasesByPublishDate); }); }) ); } function printArr() { ajaxCalls().then((values) => { console.log(values); }).catch(e => { console.error(e) }); } printArr();

Promise.allSettled gives you a signal when all the input promises are settled, which means they're either fulfilled or rejected. Promise.allSettled会在所有输入承诺都已结算时向您发出信号,这意味着它们要么被履行,要么被拒绝。 This is useful in cases where you don't care about the state of the promise, you just want to know when the work is done, regardless of whether it was successful.这在您不关心 promise 的 state 的情况下很有用,您只想知道工作何时完成,而不管它是否成功。

 var authcodes = ["E06000001", "E06000002", "E06000003"]; function ajaxCalls() { return Promise.allSettled( authcodes.map((code, i) => { return new Promise(async (resolve, reject) => { if (i ===0 ) reject('something went wrong') const response = await fetch( `https://api.coronavirus.data.gov.uk/v1/data?filters=areaCode=${code}&structure={"areaCode":"areaCode","cumCasesByPublishDate":"cumCasesByPublishDate"}` ); const json = await response.json(); resolve(json.data[0].cumCasesByPublishDate); }); }) ); } async function printArr() { const results = await ajaxCalls(); console.log(results.map((result) => result.value || result.reason)); } printArr();

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

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