js 同步异步---理解 async/await

372 阅读2分钟

2023百度前端实战训练营 (1.4)

速览

  • js 单线程是指:解析js的引擎是按单线程去解析js 的

  • 单线程任务也称作为同步任务: 程序语言中的同步与现实生活中的同步恰好是相反的概念,js语言中的同步是指,必须先执行完上一步的程序,在执行下一步的程序,而不是同时执行

  • 同步任务:先执行完上面的程序,再执行下面的程序,如果程序执行不下去有问题叫做线程阻塞。 异步任务:是指同时执行不同程序,异步就是用来解决线程阻塞的问题,因为某个程序耗时太久,导致后面的程序无法执行

  • 同步:所谓同步,就是在发出一个功能调用时,在没有得到结果之前,该调用就不返回。也就是必须一件一件事做,等前一件做完了才能做下一件事

  • 异步:异步的概念和同步相对。当一个异步过程调用发出后,调用者不能立刻得到结果。实际处理这个调用的部件在完成后,通过状态、通知和回调来通知调用者

async 函数

  • 一个语法糖 是异步操作更简单
  • 返回值 返回值是一个 promise 对象
  • return 的值是 promise resolved 时候的 value
  • Throw 的值是 Promise rejected 时候的 reason
async function test() {
  return true
}
const p = test()
console.log(p) // 打印出一个promise,状态是resolved,value是true

//  Promise {<fulfilled>: true}
//   [[Prototype]]: Promise
//   [[PromiseState]]: "fulfilled"
//   [[PromiseResult]]: true

p.then((data) => {
  console.log(data) // true
})
async function test() { throw new Error('error') }
const p = test() console.log(p) 
// 打印出一个promise,状态是rejected,value是error
p.then((data) => { console.log(data) 
//打印出的promise的reason 是error })

await 函数

  • 只能出现在 async 函数内部或最外层

  • 等待一个 promise 对象的值

  • await 的 promise 的状态为 rejected,后续执行中断

5cf8092c341646f8b020a96ca2167cd2_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

async function async1() 
{ console.log('async1 start') 
await async2() 
// await为等待promise的状态,然后把值拿到 console.log('async1 end') }
async function async2()
{ return Promsie.resolve()
.then(_ => { console.log('async2 promise') }) } 
async1()
/* 打印结果 async1 start async2 promise async1 end */

  


async 函数实现原理

实现原理:Generator+自动执行器

async 函数是 Generator 和 Promise 的语法糖

(其余)小程序项目--网络请求代码的重构和封装

分层架构

1.把网络请求抽取到services文件夹中:
封装成类,取实例对象

2.把向mv的网络请求封装到video.js里:
在调用时即可自定义 offset limit

3.抽取展示视频组件 在js文件里面,properties存放itemData接收页面传来的数据

(wxss背景图片不可以使用本地)