用Axios承诺所有人

ann*_*123 20 javascript promise axios

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

所以考虑有3个URL,让我们这样称呼它

let URL1 = "https://www.something.com"
let URL2 = "https://www.something1.com
let URL3 = "https://www.something2.com"
Run Code Online (Sandbox Code Playgroud)

还有一个我们将存储Value的数组

  let promiseArray = []
Run Code Online (Sandbox Code Playgroud)

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

axios.get(URL).then((response) => {
}).catch((error) => {
})
Run Code Online (Sandbox Code Playgroud)

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

Ngu*_*You 32

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

Promise.all()要求承诺的阵列.例如:

Promise.all([promise1, promise2, promise3])
Run Code Online (Sandbox Code Playgroud)

好吧...

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);
});
Run Code Online (Sandbox Code Playgroud)

您可能想知道响应值的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"]
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

  • 您可能想补充一点,即使其中一个失败,所有事情都会失败。 (6认同)

nor*_*off 10

使用Promise.allSettled它几乎相同,Promise.all但如果任何承诺拒绝,它不会整体拒绝。 Promise.allSettled只是等待所有的承诺尘埃落定,不管结果如何。

const [ first, second, third ] = await Promise.allSettled([
  fetch('https://jsonplaceholder.typicode.com/todos/'),
  fetch('https://jsonplaceholder.typicode.com/todos/'),
  fetch('https://jsonplaceholder.typicodecomtodos')
])

// P.S: you can replace fetch with axios
Run Code Online (Sandbox Code Playgroud)

得到的数组有:

  • { status:"fulfilled", value:result }成功回应
  • { status:"rejected", reason:error }对于错误。

在此输入图像描述


Tii*_*ane 7

只是添加到批准的答案 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)
  })
Run Code Online (Sandbox Code Playgroud)

  • 目前文档已弃用“axios.all” (2认同)
  • axios.all 于 2017 年被删除,使用 Promise.all 代替。https://github.com/axios/axios/issues/1042 (2认同)

Tar*_*req 6

您仍然可以使用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) => {
});
Run Code Online (Sandbox Code Playgroud)


Moh*_*faq 5

fetchData(URL) 函数发出网络请求并返回具有待处理状态的Promise对象。

networkRequestPromises 包含从getData函数返回的待处理的Promise数组。

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

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

async function getAllData(URLs){
  let networkRequestPromises = URLs.map(fetchData);
  return await Promise.all(networkRequestPromises);
}

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)})
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

  • 对代码的解释将使更好的答案 (2认同)

小智 5

希望这可能会有所帮助

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);
})
Run Code Online (Sandbox Code Playgroud)