W
W
Waniman2020-07-07 19:03:04
JavaScript
Waniman, 2020-07-07 19:03:04

How to implement a function with many AJAX requests that returns their responses?

We need a JS function that will have many different AJAX-s and it should return their values ​​so that they can then be accessed from other functions. How can I do that?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dima Polos, 2020-07-07
@dimovich85

async...await, Promise.allSettled (very fresh, piping hot - can burn you).

H
hzzzzl, 2020-07-07
@hzzzzl

async function getData() {
  const urls = {
    comments: 'https://jsonplaceholder.typicode.com/comments', 
    users: 'https://jsonplaceholder.typicode.com/users', 
    posts: 'https://jsonplaceholder.typicode.com/posts'
  }

  const data = {}

  for (const [key, value] of Object.entries(urls)) {
    const res = await fetch(value)
    data[key] = await res.json()
  }

  return data
}

console.log(await getData())

A
achubutkin, 2020-07-16
@achubutkin

let urls = [
  'https://api.github.com/users/iliakan',
  'https://api.github.com/users/remy',
  'https://api.github.com/users/jeresig'
];

// map every url to the promise of the fetch
let requests = urls.map(url => fetch(url));

// Promise.all waits until all jobs are resolved
Promise.all(requests)
  .then(responses => responses.forEach(
    response => alert(`${response.url}: ${response.status}`)
  ));

More examples here https://javascript.info/promise-api

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question