使用 Axios 承诺一切 [英] Promise All with Axios
问题描述
我刚刚阅读了一篇与 promise 相关的文章,但无法理解我们如何通过 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"
还有一个数组,我们将在其中存储 Value
And an array in which we will store Value
let promiseArray = []
现在,我想并行运行它 (Promise.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()
方法将返回一个 promise.
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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
这篇关于使用 Axios 承诺一切的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!