Reputation: 5520
It's useless to await a function, which does not even invoke it. But it would not generate a compile time error or runtime error. I can't figure out in what cases anyone would await a function.
In the following code, foo
will not be executed. Why doesn't Typescript ban it?
async function foo(){
console.log("foo");
}
async function bar(){
//correct usage should be: await foo();
await foo;
}
bar();
//generated es6 code.
function foo() {
return __awaiter(this, void 0, void 0, function* () {
});
}
function bar() {
return __awaiter(this, void 0, void 0, function* () {
yield foo;
});
}
bar();
Upvotes: 2
Views: 653
Reputation: 6153
Because await <expression>
expects <expression>
to be a Promise. If it is not a Promise (by promise definition) then the value will be wrapped into a Promise. You can investigate the async-await example for ping
from msdn.blogs
Formally you can expect await 10;
to be correct. Because you can't forbid wrapping plain objects or primitive values into Promises. Thus await foo;
works as a wrapper for plain object value foo
(functions in javascript are objects, you know that, right?)
Where would you use that?
Imagine a situation when you don't know beforehand whether operation will take time. For example, you have a cache implementation.
If the object is there in memory you don't have to read it from the source (db or web) which would be an asynchronous operation. So it is resolved synchronously (read from memory). However the interface should be the same. So you will await
a plain object.
Upvotes: 3