Javascript 用 Axios 承诺一切

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52669596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:00:32  来源:igfitidea点击:

Promise All with Axios

javascriptpromiseaxios

提问by anny123

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

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

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

所以考虑有 3 个 URL,让我们称之为这样的东西

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

And an array in which we will store Value

还有一个数组,我们将在其中存储 Value

  let promiseArray = []

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).

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

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

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

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

回答by Nguyen You

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

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

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

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

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

Well then...

好吧...

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);
});

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:

您可能想知道 的响应值是什么Promise.all()样的。那么,您可以通过快速查看此示例轻松地自己弄清楚:

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"]

For more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

更多信息:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

回答by Mohammed Ashfaq

fetchData(URL)function makes a network request and returns promise object with pending status.

Promise.allwill wait till all promises are resolved or any promise is rejected. It returns a promise and resolve with array of responses.

fetchData(URL)函数发出网络请求并返回具有挂起状态的承诺对象。

Promise.all将等到所有承诺都得到解决或任何承诺被拒绝。它返回一个承诺并解决一系列响应。

let URLs= ["https://jsonplaceholder.typicode.com/posts/1", "https://jsonplaceholder.typicode.com/posts/2", "https://jsonplaceholder.typicode.com/posts/3"]

function getAllData(URLs){
  return Promise.all(URLs.map(fetchData));
}

function fetchData(URL) {
  return axios
    .get(URL)
    .then(function(response) {
      return {
        success: true,
        data: response.data
      };
    })
    .catch(function(error) {
      return { success: false };
    });
}

getAllData(URLs).then(resp=>{console.log(resp)}).catch(e=>{console.log(e)})
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

回答by Tiisetso Tjabane

Just to add to the approved answer axios also has its of Promise.allin the form axios.allit expects a list of promises and returns an array of responses.

只是添加到批准的答案 axios 也有它Promise.all的形式,axios.all它期望一个承诺列表并返回一个响应数组。

let randomPromise = Promise.resolve(200);
axios.all([
    axios.get('http://some_url'),
    axios.get('http://another_url'),
    randomPromise
  ])
  .then((responses)=>{
    console.log(responses)
  })

回答by Trouble106

Hope this may help

希望这可能会有所帮助

var axios = require('axios');
var url1 = axios.get('https://www.something.com').then(function(response){
    console.log(response.data)
  })
var url2 = axios.get('https://www.something2.com').then(function(response){
    console.log(response.data)
  })
var url3 = axios.get('https://www.something3.com').then(function(response){
    console.log(response.data)
  })

Promise.all([url1, url2, url3]).then(function(values){
  return values
}).catch(function(err){
  console.log(err);
})

回答by Tareq

You still can use promise.allwith array of promises passed to it and then wait for all of them to be resolved or one of them gets rejected.

您仍然可以使用promise.all传递给它的一系列承诺,然后等待所有承诺得到解决或其中一个被拒绝。

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


const fetchURL = (url) => axios.get(url);

const promiseArray = [URL1, URL2, URL3].map(fetchURL);

Promise.all(promiseArray)
.then((data) => {
  data[0]; // first promise resolved 
  data[1];// second promise resolved 
})
.catch((err) => {
});

回答by sol404

Something like this should work:

这样的事情应该工作:

const axios = require('axios');
function makeRequestsFromArray(arr) {
    let index = 0;
    function request() {
        return axios.get('http://localhost:3000/api/' + index).then(() => {
            index++;
            if (index >= arr.length) {
                return 'done'
            }
            return request();
        });

    }
    return request();
}

makeRequestsFromArray([0, 1, 2]);