从异步调用返回一个数组,然后对数组的每个元素进行额外的异步调用 [英] Return an Array from an Async call, then additional Async calls for each element of the array

查看:26
本文介绍了从异步调用返回一个数组,然后对数组的每个元素进行额外的异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 javascript 编写一个应用程序,我向服务器发出 CORS 请求以获取数据数组.

I'm writing an application in javascript where I make a CORS request to the server to grab a data array.

然后,对于数组中的每个项目,我需要进行另一个 CORS 调用以获取有关该元素的其他信息.

Then, for each item in the array, I need to make another CORS call to get additional info on that element.

我最初认为我可以从我的 CORS 请求中返回值,例如:

I originally thought I could return values from my CORS request like:

data = getData(param);

但显然你不能混合同步和异步代码.

But apparently you can't mix synchronous and asynchronous code.

实现这一目标的最佳方法是什么?

What's the best way to accomplish this?

推荐答案

Promises.以下是根据您的要求使用它们的方法,以及一个 setTimeout 来模拟 AJAX 请求.

Promises. Here's how you might use them using your requirements, and a setTimeout to mimic an AJAX request.

getData 返回一个新的承诺.在这种情况下,如果在没有参数的情况下调用该函数,则一秒钟后(您的第一个请求)将返回一个数组.如果参数被传递到函数中,100 会在解析之前添加到参数中 - 后面的请求.

getData returns a new promise. In this case if the function is called with no params an array is sent back after a second (your first request). If a param is passed into the function 100 is added to the param before resolving - the later requests.

function getData(param) {
  return new Promise(function(resolve, reject) {
    if (param) {
      setTimeout(() => resolve(param + 100), 500);
    } else {
      setTimeout(() => resolve([1, 2, 3, 4, 5]), 1000)
    }
  });
}

不带参数调用getData,返回[1, 2, 3, 4, 5].then 我们映射数组元素并为每个元素返回 new 承诺.then 我们使用 Promise.all 来解析这些 Promise 并且 then 我们输出最终的数组 [101, 102, 103, 104,105].

Call getData without a param and [1, 2, 3, 4, 5] is returned. then we map over the array elements and return new promises for each of them. then we use Promise.all to resolve those promises and then we output the final array [101, 102, 103, 104, 105].

getData()
  .then((arr) => arr.map(el => getData(el)))
  .then(arr => Promise.all(arr))
  .then(arr => console.log(arr));

演示

因此您可以看到,您可以运行一个 AJAX 请求,然后根据返回值的结果运行更多请求,直到发出所有请求.

So you can see that you can run one AJAX request and then run more based on the result of the value that's returned until all requests have been made.

这篇关于从异步调用返回一个数组,然后对数组的每个元素进行额外的异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆