Promises and Static Values
Publikováno: 23.8.2019
Async can throw a real wrench into the cogs of our programming workflows, all despite the fact that async is the modern JavaScript pattern. While async/await helps, there’s sometimes confusion about the way to have a single function that returns a value whether it exists or needs a Promise to retrieve. To return an existing […]
The post Promises and Static Values appeared first on David Walsh Blog.
Async can throw a real wrench into the cogs of our programming workflows, all despite the fact that async is the modern JavaScript pattern. While async/await helps, there’s sometimes confusion about the way to have a single function that returns a value whether it exists or needs a Promise to retrieve.
To return an existing (or cached) value or the result of a promise from a single function, you employ a quick new Promise(resolve)
:
async function getValueOrFetch(ojbOrInfo) { // If the value exists, immediately return it if(ojbOrInfo) { return new Promise(resolve => resolve(ojbOrInfo)); } // Return the promise-based info return asyncFunctionToGetInfo(ojbOrInfo); }
Here’s an example of using a cache with the Promise API:
const cache = { /* url: content */ }; // Async function that returns cached content or retrieves fresh content async function getInfo(url) { // Check for value in cache if (cache[url]) { // Return a value from cache with a quick promise return new Promise(resolve => resolve(cache[url])); } // Get the content fresh const content = await fetch("https://www.facebook.com").then(r => r.text()); cache[url] = content; return new Promise(resolve => resolve(content)); }
My main goal with this post is making you understand that return new Promise(resolve => resolve(data))
is the way to return static or known data from a Promise-based interaction. The return value from an async function needs to be a Promise and so new Promise(resolve => resolve(data))
is the best way to return known data!
The post Promises and Static Values appeared first on David Walsh Blog.