I'm working in an Angular/AngularJs hybrid application with TypeScript (versions 9.07, 1.5.11, and 3.7.5, respectively). All of our HTTP requests, even the ones made from new Angular ponents, use a wrapper service implemented in plain Javascript, originally developed along with the "legacy" AngularJs side of the application, whose methods return $q promises generated by the AngularJs $http service. Since that service is plain Javascript, typing of return values isn't a problem, since TypeScript considers them just an any
, which it's perfectly happy to let me cast as an IPromise<TReturnType>
.
My question is whether those promises are fully patible with the async
and await
keywords in TypeScript. Trying it out with simple examples seemed to work fine, but I'm concerned about corner-case problems that would only show up at runtime using those keywords with non-native Promises.
I'm working in an Angular/AngularJs hybrid application with TypeScript (versions 9.07, 1.5.11, and 3.7.5, respectively). All of our HTTP requests, even the ones made from new Angular ponents, use a wrapper service implemented in plain Javascript, originally developed along with the "legacy" AngularJs side of the application, whose methods return $q promises generated by the AngularJs $http service. Since that service is plain Javascript, typing of return values isn't a problem, since TypeScript considers them just an any
, which it's perfectly happy to let me cast as an IPromise<TReturnType>
.
My question is whether those promises are fully patible with the async
and await
keywords in TypeScript. Trying it out with simple examples seemed to work fine, but I'm concerned about corner-case problems that would only show up at runtime using those keywords with non-native Promises.
1 Answer
Reset to default 8Compatibility with async
is not an issue, as that keyword does not directly depend on an existing promise instance: it makes the corresponding function return a newly created EcmaScript Promise object.
If an async
function returns a thenable, then the returned native promise will have its resolution made dependent on that thenable.
You can see that latter effect in this snippet:
async function test() {
let thenable = { then: cb => cb(13) };
return thenable;
}
let result = test();
console.log(result instanceof Promise);
result.then(console.log); // 13
The await
keyword can be used with an expression that returns a thenable, so also in that case there is no requirement to have an EcmaScript patible promise:
async function test() {
let thenable = { then: cb => cb(13) };
let value = await thenable;
console.log(value); // 13
}
test();
So in conclusion, both keywords will recognise a thenable and deal with it as expected. There is no requirement that this thenable is an instance of the native Promise.
Surely $q
promises are thenables, so that is just fine.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744947036a4602682.html
评论列表(0条)