user13294667
user13294667

Reputation:

Store promises in multiple variables of async function

Is it possible to store the data of resolved promises in multiple variables using a async/await function?

E.g.

const urls = [
    'https://jsonplaceholder.typicode.com/users',
    'https://jsonplaceholder.typicode.com/posts'
]

const getData = async function() {
    const Promises = urls.map(url => fetch(url))
    for await (let request of Promises) {
        const data = await request.json()
    }
}

getData()

// However, I want to store '/users' in 'const users', '/posts' in 'const posts' etc.

Upvotes: 0

Views: 46

Answers (1)

Bergi
Bergi

Reputation: 664920

You seem to be looking for

async function getData() {
    const promises = [
        'https://jsonplaceholder.typicode.com/users',
        'https://jsonplaceholder.typicode.com/posts'
    ].map(url =>
        fetch(url).then(request => request.json())
    );
    const [users, posts] = await Promise.all(promises);
    console.log(users, posts);
}

Upvotes: 1

Related Questions