'How to wait for chrome.storage.sync.set to finish storing data before continuing execution of a program( chrome extension)?

I'm working on chrome extension. I have function that needs to wait for asynchronous chrome.storage.set to set data and after that use that stored value.

Example: this function is setting access token in chrome storage

 async setAuthTokenInStorage(token) {
    const dataToStore = {accessToken : token.access_token, refreshToken : token.refresh_token };
     chrome.storage.sync.set({ token: dataToStore });
},

After this function, we immediately run one HTTP request in a different place in application. HTTP request will use new token. But that request fails because data is not stored yet, and http request already failed.

Is there some way that we can wait for setAuthTokenInStorage() to finish executing.Meaning that we will make this method 'synchronous' somehow. Goal is to make this function end only when data is stored.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source