用Axios承诺所有人 [英] Promise All with Axios

查看:87
本文介绍了用Axios承诺所有人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了一篇与承诺相关的文章,并且无法理解我们如何通过Promise.all 使用Axios进行多次API调用

I just read an Article related to promise and was unable to comprehend how we can do multiple API call using Axios via Promise.all

所以考虑有3个URL,让我们称之为

So consider there are 3 URL, lets call it something like this

let URL1 = "https://www.something.com"
let URL2 = "https://www.something1.com
let URL3 = "https://www.something2.com"

我们将存储值的数组

  let promiseArray = []

现在,我想并行运行(承诺.all ),但我无法确定我们将如何做到这一点?因为axios本身就有承诺(或者至少我是如何使用它的。)

Now, I want to run this in parallel (Promise.all), but I am unable to figure our how will we do it? Because axios have a promise in itself (or at-least that's how I have used it).

axios.get(URL).then((response) => {
}).catch((error) => {
})

问题:有人可以告诉我怎么样我们可以使用promise.all和axios发送多个请求

Question: Can someone please tell me how we can we send multiple request using promise.all and axios

推荐答案

axios.get()方法将返回一个承诺。

The axios.get() method will return a promise.

Promise.all()需要一系列承诺。例如:

The Promise.all() requires an array of promises. For example:

Promise.all([promise1, promise2, promise3])

那么......

let URL1 = "https://www.something.com"
let URL2 = "https://www.something1.com"
let URL3 = "https://www.something2.com"

const promise1 = axios.get(URL1);
const promise2 = axios.get(URL2);
const promise3 = axios.get(URL3);

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});

您可能想知道 Promise.all()的响应值看起来像。那么,你可以通过快速查看这个例子轻松搞清楚:

You might wonder how the response value of Promise.all() looks like. Well then, you could easily figure it out yourself by taking a quick look at this example:

var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]

更多信息: https://developer.mozilla。 org / zh-CN / docs / Web / JavaScript / Reference / Global_Objects / Promise / all

这篇关于用Axios承诺所有人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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