Yes, but if I am ok with stopping the world, why doesn't JS allow me to do so? Why do we need to have an entirely seperate api for sync http calls when allowing awaiting inside sync functions would have done the same thing?
¹Not really, but close enough.
Originally, this was resolved via callbacks:
doSomething((err, result) => {
if (err) { ...failure code... }
...success code...
}
But that got very clunky, resulting in something called "callback hell" and the "callback pyramid of doom." So promises were introduced: doSomething().then((result) => {
...success code...
}).catch((err) => {
...failure code...
});
But that's also clunky, so the async/await syntax was introduced: try {
let result = await doSomething();
...success code...
}
catch (err) {
...failure code...
}
And that's actually quite pleasant to use. 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()) 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')> async function run() {
// call your program logic here
await myCode()
}> run()
function A(){ B()}
function B(){ C()}
...
function Y(){ await? Z()}
async function Z(){...}
Then A-Y would need to become async. If await Z() was allowed then we could avoid this. So is there a reason why it could not be implemented this way?