typescript Async/Await ,简单示例(打字稿)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32401741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Async/Await , simple example (typescript)
提问by Pranay Dutta
I am quite familiar with the async/await of c# and been using typescript for a year or so, can anyone please give a simple example explaining how it works on typescript?? Thanks in advance , looking forward to find some help and implement the same
我非常熟悉 c# 的 async/await 并且已经使用 typescript 一年左右了,谁能举一个简单的例子来解释它是如何在 typescript 上工作的?提前致谢,期待找到一些帮助并实现相同的
UPDATE
it would be very helpful if the example includes angular/jquery promise, as it will give a clear view of practical implementation
更新
如果示例包含 angular/jquery 承诺将非常有帮助,因为它将清楚地了解实际实现
回答by David Sherret
The key is to use an ES6 Promiseor something that implements the PromiseLike
and PromiseConstructorLike
interfaces found in lib.d.ts(Read more). A jQuery promise does not implementthese interfaces so it won't work with that.
关键是使用ES6 Promise或实现lib.d.ts 中的PromiseLike
和PromiseConstructorLike
接口的东西(阅读更多)。jQuery 承诺没有实现这些接口,因此它不会与这些接口一起工作。
Here's a simple example using an ES6 promise:
这是一个使用 ES6 承诺的简单示例:
function getStringFromWebServerAsync(url: string) {
return new Promise<string>((resolve, reject) => {
// note: could be written `$.get(url).done(resolve).fail(reject);`,
// but I expanded it out for clarity
$.get(url).done((data) => {
resolve(data);
}).fail((err) => {
reject(err);
});
});
}
async function asyncExample() {
try {
const data = await getStringFromWebServerAsync("http://localhost/GetAString");
console.log(data);
}
catch (err) {
console.log(err);
}
}
asyncExample();
Note that any code containing an await
statement needs to be within an async
function and so I have wrapped the code in one. That said, an upcoming proposal adds "top-level await", which will be available in TypeScript 3.8. Read more hereand see here for TypeScript details.
请注意,任何包含await
语句的代码都需要在一个async
函数中,因此我将这些代码合二为一。也就是说,即将到来的提案添加了“顶级等待”,它将在 TypeScript 3.8 中可用。在此处阅读更多信息并在此处查看 TypeScript 详细信息。
回答by Zartag
Please note that you need to target ES6 in Typescript 1.7 to use async/await. With lower versions, Visual Studio outputs
请注意,您需要在 Typescript 1.7 中以 ES6 为目标才能使用 async/await。对于较低版本,Visual Studio 输出
TS1308 'await' expression is only allowed within an async function.
and
和
TS1311 Async functions are only available when targeting ECMAScript 6 and higher.
For more information see e.g. http://blogs.msdn.com/b/typescript/archive/2015/11/03/what-about-async-await.aspx
有关更多信息,请参见例如http://blogs.msdn.com/b/typescript/archive/2015/11/03/what-about-async-await.aspx