Created
September 16, 2021 04:26
-
-
Save lusan/802d4ba5578425537ce07743af9b751d to your computer and use it in GitHub Desktop.
async localstorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Source: https://stackoverflow.com/questions/42921220/is-any-solution-to-do-localstorage-setitem-in-asynchronous-way-in-javascript | |
// localStorage is a synchronous API. You could defer the setItem method execution with the Promise object, giving them an asynchronous behaviour: | |
const asyncLocalStorage = { | |
setItem: function (key, value) { | |
return Promise.resolve().then(function () { | |
localStorage.setItem(key, value); | |
}); | |
}, | |
getItem: function (key) { | |
return Promise.resolve().then(function () { | |
return localStorage.getItem(key); | |
}); | |
} | |
}; | |
// Demo | |
const data = Date.now() % 1000; | |
asyncLocalStorage.setItem('mykey', data).then(function () { | |
return asyncLocalStorage.getItem('mykey'); | |
}).then(function (value) { | |
console.log('Value has been set to:', value); | |
}); | |
console.log('waiting for value to become ' + data + | |
'. Current value: ', localStorage.getItem('mykey')); | |
// See it run on repl.it, as SO snippets do not allow the use of localStorage. | |
// With the newer async/await syntax, this asyncLocalStorage can be written as: | |
const asyncLocalStorage = { | |
setItem: async function (key, value) { | |
await null; | |
return localStorage.setItem(key, value); | |
}, | |
getItem: async function (key) { | |
await null; | |
return localStorage.getItem(key); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment