上一篇
TypeScript如何返回Promise
- 行业动态
- 2024-04-15
- 2
在TypeScript中,返回Promise的方法如下:
1、使用new Promise()
构造函数创建一个新的Promise对象。
2、在Promise的执行器函数(executor function)中使用resolve()
和reject()
方法来改变Promise的状态。
3、使用then()
和catch()
方法处理Promise的成功和失败情况。
下面是一个简单的示例:
function asyncFunction(): Promise<string> { return new Promise((resolve, reject) => { setTimeout(() => { const result = "Hello, World!"; resolve(result); }, 1000); }); } asyncFunction() .then((result) => { console.log(result); // 输出 "Hello, World!" }) .catch((error) => { console.error(error); });
在这个示例中,我们定义了一个名为asyncFunction
的异步函数,它返回一个Promise对象,在Promise的执行器函数中,我们使用setTimeout()
模拟异步操作,并在1秒后调用resolve()
方法将Promise状态改为已成功(fulfilled),并传递结果值,我们使用then()
和catch()
方法处理Promise的成功和失败情况。