• async/await


    https://mp.weixin.qq.com/s/ZSDPMSjA4hYh1ECSv5ClHw

    https://mp.weixin.qq.com/s/gJqMT7w-N5JgZQi5T54ggg

     1 fn = () => {
     2 
     3   return new Promise((resolve, reject) => {
     4 
     5     setTimeout(() => {
     6 
     7       resolve(1)
     8 
     9     }, 2000)
    10 
    11   })
    12 
    13 }
    14 
    15 const Fn = () =>{
    16 
    17   fn().then((res) => {
    18 
    19     console.log(res)
    20 
    21   })
    22 
    23 
    24   console.log(2)
    25 
    26 } 
    27 
    28 
    29 Fn()  //先打印 2,2s 之后打印出 1。
     1 fn = () => {
     2 
     3   return new Promise((resolve, reject) => {
     4 
     5     setTimeout(() => {
     6 
     7       resolve(1)
     8 
     9     }, 2000)
    10 
    11   })
    12 
    13 }
    14 
    15 const Fn = async () => {
    16 
    17   await fn().then((res) => {
    18 
    19     console.log(res)
    20 
    21   })
    22   console.log(2)
    23 }
    24 
    25 Fn() //2s 后打印 1,然后打印 2。

    我们在字面上理解这两个单词 async 和 await:async 的意思是异步,async 用于定义一个异步函数,该函数返回一个 Promise。;await 的意思是等待,Promise 是一个承诺,await 也是一个承诺。Promise 的承诺是将返回值输出到 then 的回掉函数里面,无论是成功还是失败。await 的承诺是无论刮风还是下雨,我都会等你完成在做其他的步骤。因此,在上面的运用了 async/await 的代码中,会等待 fn 完全运行完成并且异步的回调完成对返回值的处理之后在开始进行下一步操作的。其原理是将异步函数转变为同步操作。

  • 相关阅读:
    【C】中malloc的使用
    【C++】const成员函数的作用
    C声明和定义
    【C++】指针与引用的区别
    【C】external/internal/static/register variable and function
    【C++】Sizeof与Strlen
    【面试题目】string类实现
    【C++】public,private,protected
    【Linux】僵尸进程
    【面试题目】翻转句子中单词的顺序
  • 原文地址:https://www.cnblogs.com/ftxc/p/9115628.html
Copyright © 2020-2023  润新知