指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

async和await的使用深入研究:

官方文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#conversion_to_promise
        
// useAuth.ts
interface UserInfo {
  id: number
  name: string
  email: string
  // 根据实际用户信息结构定义其他属性
}
  
const getUserInfo = async (): Promise<UserInfo> => {
    try {
      // 调用获取用户信息 API, 这里测试,直接返回结果,实际课通过 await ¥fetch() 获取数据
      const response = {id:1, name: "jerry", email: "ererer@gmai.com"}

     return response
    
    } catch (error) {
      // 处理错误
      console.error(error)
      throw error
    }
}
  
const f1 = async () =>{
    const user =  await getUserInfo()
    console.log("user is:", user)
}

f1();
  
//
async function f2() {
  const thenable = {
    then(resolve: (arg0: string) => void, _reject: any) {
      resolve("resolved!");
    },
  };
  console.log(await thenable); // "resolved!"
}

f2();
  
//
async function f3() {
  const y = await 20;
  console.log(y); // 20

  const obj = {};
  console.log((await obj) === obj); // true
}

f3();
  
//
async function f4() {
  try {
    const z = await Promise.reject(30);
  } catch (e) {
    console.error(e); // [ERR]: 30
  }
}

f4();
  
语法:
await expression
  
关于await的作用:
await is usually used to unwrap promises by passing a Promise as the expression. Using await pauses the execution of its surrounding async function until the promise is settled (that is, fulfilled or rejected). When execution resumes, the value of the await expression becomes that of the fulfilled promise.
  
使用原理:
The expression is resolved in the same way as Promise.resolve(): it's always converted to a native Promise and then awaited
  
表达式的三种体现:
1>Native Promise (which means expression belongs to Promise or a subclass, and expression.constructor === Promise): The promise is directly used and awaited natively, without calling then().
2>Thenable object (including non-native promises, polyfill, proxy, child class, etc.): A new promise is constructed with the native Promise() constructor by calling the object's then() method and passing in a handler that calls the resolve callback.
3>Non-thenable value: An already-fulfilled Promise is constructed and used.