从异步调用返回一个数组,然后附加异步调用的阵列中的每个元素 [英] Return an Array from an Async call, then additional Async calls for each element of the array

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

问题描述

我写在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);

但很显然,你不能混用同步和异步code。

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

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

What's the best way to accomplish this?

推荐答案

承诺。以下是你可能会如何使用您的要求使用它们,和的setTimeout 来模拟一个AJAX请求。

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

的getData 返回一个新的承诺。在这种情况下,如果调用函数时没有PARAMS数组是第二个(你的第一个要求)后送回。如果一个参数是传递给函数 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] 被返回。 然后我们映射在数组元素,并返回的新的的承诺,为他们每个人。 然后我们使用 Promise.all 来解决这些承诺和然后我们输出最终阵列 [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天全站免登陆