0
点赞
收藏
分享

微信扫一扫

使用极狐GitLab进行K3S集群的维护与控制

小黑Neo 2024-08-29 阅读 6

当一个函数被声明为 async function 时,这意味着这个函数总是会返回一个 Promise 对象。即使在函数中没有显式使用 await 来等待一个 Promise 的解决,这个函数仍然会隐式地返回一个解决的 Promise。

下面两段代码是等同的

  async function asyncFn() {
      return 'hello world';
  }

function fn() {
    return new Promise((resolve, reject) => {
	     resolve('hello world');
    });
  }

当你调用这个函数时,你可以像下面这样处理返回的 Promise:

function fn() {
    return new Promise((resolve, reject) => {
        reject('error');
    //   resolve('hello world');
    });
  }

  
  fn().then(result => {
    console.log(result); // 输出: 'hello world'
  }).catch(err => {
      console.log(err); // 输出: 'error'
  })

  async function asyncFn() {
      return 'hello world';
  }

  asyncFn().then(result => {
    console.log(result); // 输出: 'hello world'
  })
举报

相关推荐

0 条评论