Category: PHP, api, javascript
Let’s talk about parallel promises today. So, in JavaScript, Promises provides a way of doing asynchronous programming in the language.
Let’s take the following example where we are fetching posts, photos, and todos of a user.
async function fetchUserResources() { const posts = await fetch('https://jsonplaceholder.typicode.com/posts/1'); // Takes 2 seconds const photos = await fetch('https://jsonplaceholder.typicode.com/photos/1'); // Takes 2 seconds const todos = await fetch('https://jsonplaceholder.typicode.com/todos/1'); // Takes 2 seconds return {posts, photos, todos}; }
async function fetchUserResources() { const [posts, photos, todos] = await Promise.allSettled([ fetch('https://jsonplaceholder.typicode.com/posts/1'), fetch('https://jsonplaceholder.typicode.com/photos/1'), fetch('https://jsonplaceholder.typicode.com/todos/1')]); console.log(posts); // {status: "fulfilled", value: {"holds_the_posts_object"}} console.log(photos); // {status: "fulfilled", value: {"holds_the_photos_object"}} console.log(todos); // {status: "rejected", reason: The error} return {posts, photos, todos}; }