Resolved JavaScript Promises Can Be Used Multiple Times!

Premier Developer

Premier

In this post, App Dev Manager Ashley Grant shows how to cache data in JavaScript Promises.


JavaScript Promises are powerful, and they become more powerful once we understand that a “resolved” Promise can be used more than once! How can we use this in a “real” application? Maybe you have a button in your application that will display user information when clicked. You could wait to make the fetch call until the button is clicked, and then save this Promise in a variable. In future calls, the code will see that this Promise already exists, and thus skip calling fetch again.

Something like this:

let fetchUsers;   

document.getElementById('displayUser').onclick = () => {
  if(!fetchUsers) {
    fetchUsers = fetch('https://api.github.com/users')
      .then( response => response.json());
  } 
  
  const index = document.getElementById('index').value;
  
  fetchUsers.then(users => {
    document.getElementById('userName').innerHTML = users[index].login;
  });
};

Read the full article here.

0 comments

Leave a comment