异步你怎么理解

88 阅读1分钟
  • js代码执行的顺序是:先同步代码,再微任务,再宏任务

  • 问:微任务和宏任务区别

    • 微任务属于ecmascript内置的语法,比如promise,async,await
    • 宏任务属于webapi的东西,本质是属于宿主环境的东西
  • promise相关

    • promise的三种状态 pending fullfiled rejected 待定 成功 失败

    • promise的实例方法 then catch finally

    • promise的静态方法 all allSettled race any

      • all是拿到所有的成功的数组,只要有一个失败就直接失败了
      • allSettled 不管成功失败,会得到数组
      • race 拿第一个结果 不在乎成功还是失败
      • any 拿第一个成功的结果
    • 值穿透 then如果里面不是callback函数而是一个普通的值,它会把值传到下一个then,直到有callback为止

  • async,await

    • async,await是promise的语法糖
  • generator

    • 也是一种异步的解决方法
    • 翻译过来叫生成器
function* fn(){
    yield 2
    yield 3 
    yield 4  
}

const gen = fn()
console.log(gen.next())
console.log(gen.next())
console.log(gen.next())
  • 迭代器 数组、字符串、数字、伪数组、生成器

  • for..in,for..of的区别

    • for...in 一般是用来遍历对象
    • for..of是用来遍历迭代器 (数组、字符串、数字、伪数组、生成器)
  • for..in能不能遍历数组

    • 可以,但是不推荐,因为for..in是把数组当成普通,所以会造成数组上有非索引相关的属性也会被遍历出来
const arr = [2, 3, 4]
arr.a = 200
for (let key in arr) {
    console.log(arr[key]);
}