I am writing some code to simulate a Database call that I only want to make once, and store the result in a map (to prevent repeated round trips).
My code seems to work fine, but I am getting an unexpected result: when I remove one of the await values (highlighted below), the code appears to wait on the resolution of the promise (in that the console.log still waits for 5 seconds), but the logged value is still a Promise.
In my mind, this seems inconsistent, so I think my understanding of Promises might be lacking.
const inputs = ['a', 'b'];
let promiseOrValue
async function processor(input){
if (promiseOrValue){
await promiseOrValue
}
else {
promiseOrValue = asyncFunction()
await promiseOrValue
}
console.log(`${input} ${**await** promiseOrValue}`)
}
async function asyncFunction(){
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('resolving')
resolve('foo')
}, 1000)
})
}
inputs.forEach(processor)
I expect that either the console.log will print immediately with [object Promise]
, or it will wait 5 seconds and print foo
. In fact, it waits 5 seconds, and then prints [object Promise]
.