简体   繁体   English

处理来自异步调用的数据

[英]Manipulate data from an async call

I have two functions, 我有两个功能,

function getRequest(url, api_key, callback) {
    $.ajax({
        url: url,
        contentType: 'application/json',
        type: 'get',
        beforeSend: function(xhr){
            xhr.setRequestHeader('Authorization', 'Bearer ' + api_key);
        },
        success: function(response) {
            callback(response);
        },
        error: function(error) {
            console.log(error);
            document.getElementById("droplets").textContent = error;
        }
    });
}

function getDroplets(url, api_key) {
    var request = getRequest(url, api_key, function(response) {
        var droplets = response.droplets;
        var numDroplets = droplets.length;
        return {
            droplets: droplets,
            numDroplets: numDroplets
        };
    });
    alert(request);
}

I want to have another function, let's call it listDroplets , that will call getDroplets() and manipulate the data returned from it. 我想要另一个函数,让我们将其listDroplets ,它将调用getDroplets()并处理从其返回的数据。 I'm not sure how to do this because getDroplets has an asynchronous call within it. 我不确定如何执行此操作,因为getDroplets具有异步调用。

EDIT: I have tried the following, but it still doesn't work. 编辑:我已经尝试了以下方法,但仍然无法正常工作。

async function listDroplets() {
    await getDroplets(api_url, api_key);
    alert(request.numDroplets);
}

Here are how your functions could return promise like objects that you can use in an async await function: 这是您的函数如何返回承诺(例如可以在异步await函数中使用的对象)的方式:

function getRequest(url, api_key, callback) {
  //to escape terrible jQuery Deferred and comfortably continue in Promise land
  // you can do
  // const deferred = $.ajax(...); return Promise.resolve(deferred)
  return $.ajax({//return promise like object
    url: url,
    contentType: 'application/json',
    type: 'get',
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + api_key);
    }
  });
}

function getDroplets(url, api_key) {
  return getRequest(url, api_key)//return promise like object
  .then(function (response) {//
    var droplets = response.droplets;
    var numDroplets = droplets.length;
    return {
      droplets: droplets,
      numDroplets: numDroplets
    };
  })
  .catch(function (error) {//implement error if something goes wrong
    console.log(error);
    document.getElementById("droplets").textContent = error;
  });
}


async function listDroplets() {
  //depending on how old your jQuery is you may want to do this:
  // await Promise.resolve(getDroplets(api_url, api_key));
  const request = await getDroplets(api_url, api_key);
  //note that if something goes wrong then request is undefined (depending on jQuery version)
  alert(request.numDroplets);
}

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

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