Let a function which returns a promise:
async function foo() {
return await new Promise((res, rej) => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => res.json())
.then(data => res(data))
.catch(err => rej(err))
})
}
In order to reuse the returned data I can think something like:
(async function() {
data = await foo().catch(err => console.log('err: ', err))
fnc1(data)
fnc2(data)
...
fncn(data)
})();
or something like:
foo().then(data => {
fnc1(data)
fnc2(data)
...
fncn(data)
}
)
So always I have to go back in my code find the function or callback which gets the data returned by the promise and include any new function that I want to the appropriate block.
I was wondering if there is any smarter way to achieve the same result in javascript. I know that something like the following won't work:
var dataFromPromise
foo().then(data => dataFromPromise = data)
console.log(dataFromPromise) //undefined if called before foo runs