3 ms·
I haven't tried it and surely not recommended, but I think it's possible to block execution with a while loop until the promise is resolved/rejected. This will
by lioeters 5y ago
I haven't tried it and surely not recommended, but I think it's possible to block execution with a while loop until the promise is resolved/rejected. This will be like a "synchronous await", which defeats the purpose of having async functions.
function syncFn() {
let result
let state = 'pending'
asyncFn()
.then(data => {
result = data
state = 'fulfilled'
})
.catch(error => {
result = error
state = 'rejected'
})
while(state==='pending') {} // Stop the world
return result
}
console.log('Result', syncFn())
- maple3142 5y agoI don't think this will work in JavaScript because that while loop will block the event loop and prevents callback from executing. For example, the following code will be blocked when running in Node.js: function delayedValue(val, ms) { return new Promise(resolve => setTimeout(() => resolve(val), ms)) } function syncFn() { let result let state = 'pending' delayedValue(1234, 500) .then(data => { result = data state = 'fulfilled' }) .catch(error => { result = error state = 'rejected' }) while (state == 'pending') {} return result } console.log('before') console.log(syncFn()) console.log('after')