How do you turn on/off await? The only way to use await is inside an async function(){}
or async ()=>{}
, so there's no way to know ahead-of-time whether to make your code async or not if you are going to be using await
. Here's a demonstrification of how await
works under the hood:
async await_demonstrification(value) {
if (typeof value === "object" && "then" in value && typeof value.then === "function") {
return await value;
} else {
return value;
}
}
The only way I can think of to switch between async and sync is to write the code twice, which is less than ideal and something that your proposal does not solve:
// Less maintainable dual sync/async version:
function maybeAsync(model) {
if (model instanceof Promise) {
return async function() {
return await (await model).getList(); // async
};
} else {
return model.getList(); // sync
}
};
// More maintainable sync/async version:
async function alwaysAsync() {
return await (await model).getList(); // async
};
Lastly, if you really do need to use await
this way, there's already a pipeline spec which is underway and will fulfill the same purposes as you desire:
let myList = model.getList() |> isAsync ? await # : #;
Or, you could roll out your own piping system:
var X, PIPE = function(value) {X = value; return true}; // setup code
//...
let myList = PIPE(model.getList()) && isAsync ? await X : X;
// OR:
PIPE(model.getList()); let myList = isAsync ? await X : X;
If your reasoning is performance, then you need to rethink your approach. Promises will always have terrible performance and should only be used for the larger macro tasks, never the tiny micro tasks. For the micro tasks, always use callbacks, otherwise you will be in a world of hurt when it comes to performance.
I think you have a good proposal that may help some people, but it is much too specific and will be used so infrequently that's its not work the complexity it would add to both the language and the browsers.