There are a few different nuances to this question.
Can it be done? sure:
let bar = await foo();
return bar + 1;
can be converted to:
let resultPromise = foo();
while (!resultPromise.isComplete()){
sleep(10);
}
let bar = resultPromise.value();
return bar + 1;
the issue is that this is terribly inefficient as you are asking every 10ms whether or not the result is ready.
One of the reasons this is so inefficient is that you have to spend time checking (which is wasteful if it isnt ready) and waiting. If you check more frequently, you're wasting CPU. If you spend more time waiting, you can waste up to that much time if the result is ready right after you go to sleep.
The alternative is to have the operating system tell you when its ready. This is done through the event loop. So this would turn the code transformation into something like the following:
let resultPromise = foo().then(function(bar){
return bar + 1;
});
but what do you return? you have to return a promise (i.e. a callback). Therefore, all callers of this function have to be ready to handle this.
Not necessarily! In a typical eventloop system - like with libuv - events and readiness will be checked within the eventloop while no user code is executed. The eventloop runs something along:
while (true) {
waitForOsEventsOrTimers(); // Uses epoll & co
executeAllReadyCallbacks();
}
Your whole promise code is part of `executeAllReadyCallbacks`. Thereby any blocking there will block fetching new readiness events, and thereby the code will be stuck.
It would only work if the polling OS functions would run on a different thread - which some runtimes like .NET might actually do. However its very often avoided since its less efficient than polling events inline without synchronization, and in Javascript wouldn't work.
I don't know of a JavaScript implementation where that approach would work. A synchronous implementation of `sleep` can't yield control back to the main thread to handle the asynchronous stuff. You'd just end up polling indefinitely.
Can it be done? sure:
can be converted to: the issue is that this is terribly inefficient as you are asking every 10ms whether or not the result is ready.One of the reasons this is so inefficient is that you have to spend time checking (which is wasteful if it isnt ready) and waiting. If you check more frequently, you're wasting CPU. If you spend more time waiting, you can waste up to that much time if the result is ready right after you go to sleep.
The alternative is to have the operating system tell you when its ready. This is done through the event loop. So this would turn the code transformation into something like the following:
but what do you return? you have to return a promise (i.e. a callback). Therefore, all callers of this function have to be ready to handle this.