问题描述
我对 C# 的 async/await 非常熟悉并且已经使用 TypeScript 一年左右了,谁能举一个简单的例子来解释它在 TypeScript 中是如何工作的?
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 in TypeScript?
如果该示例包含 Angular/jQuery 承诺,将会非常有帮助,因为它会给出实际实现的清晰视图.
It would be very helpful if the example includes Angular/jQuery promise, as it will give a clear view of a practical implementation.
推荐答案
关键是使用 ES6 Promise 或实现 (阅读更多).一个 jQuery 承诺没有实现这些接口,所以它不能使用.
The key is to use an ES6 Promise or something that implements the PromiseLike
and PromiseConstructorLike
interfaces found in lib.d.ts (Read more). A jQuery promise does not implement these interfaces so it won't work with that.
这是一个使用 ES6 承诺的简单示例:
Here's a simple example using an ES6 promise:
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();
请注意,任何包含 await
语句的代码都需要在 async
函数中,因此我将代码包装成一个.也就是说,即将到来的提案添加了顶级等待",它将在 TypeScript 3.8 中可用.阅读更多此处和参见此处了解 TypeScript 详细信息.
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 here and see here for TypeScript details.
这篇关于TypeScript 中的 async/await 语法是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!