用async修饰的函数是异步函数吗?

前言:

在我们解决异步编程的时候,经常会用到async 和await编程的解决方案。

看以下的代码:

  async function fn() {
    console.log(123);
  }
  console.log(fn());

打印的是一个Promise对象。

  async function fn() {
    console.log(123);
  }
  fn()
  console.log(456);

如果修饰玩就是异步的,那么打印的结果就是456 ,123。

结果是相反的,它单纯的只是是一个Promise对象。并没有then,catch之类的。

这个时候用上await之后我们在看一下结果。

  async function fn() {
    const a1 = await 123
   console.log(a1)
  }
  fn()
  console.log(456);

view:

此时证明了一个问题,这个函数变成异步的了。

我们平常在调用接口的时候,总是   const res1=  await  异步1     const  res2= await 异步2

等待异步任务的完成返回一个结果。

通过上方的例子我们发现.不管await后面跟的是什么都是异步去执行的。

结论:

Promise对象并不都是异步去执行的。需要和await搭配起来去使用。

then是异步的,catch也是异步的......

猜你喜欢

转载自blog.csdn.net/qq_59076775/article/details/124500060