PWA study notes (c)

Introduction to basic technology

Promise:

  A ES6 the introduction of asynchronous programming solutions , through Promise object to provide a unified asynchronous state management method

  2, generally when using Promise object, you first need to be instantiated

  3, the object is instantiated Promise asynchronous state management container , Resolve () and Reject () is used for controlling the state of promise Method

  4, when the call to resolve () and reject () method can pass any value , this value will change as a listening state parameter spread out through the callback function

  5, Promise provided .then (onFulfilled, onRejected) and .catch (onRejected), etc.

     Prototype chain approach for the callback function triggered Registered State Change

Promise = the let new new Promise ((Resolve, Reject) => {
   IF ( / * Successful Operation * / ) {
    resolve(value)
  } else {
    reject(error)
  }
})

 

Promise Status:

  . 1, ' Pending ': an initial state, representative of asynchronous process is still in progress, the success or failure has not been determined

  2, ' Fulfilled ': successful operation by calling resolve () method, by state Promise 'pending' is changed to 'fulfilled'

  . 3, ' Rejected ': failed operation by calling Reject () method, the status will change to Promise 'rejected'

 

Promise of reliability:

  1, unified format: the asynchronous process Promise package will have a unified state change mode, unified and uniform API callback format

  2, the state against external influences: only method of control by the state Promise resolve () and reject (), this state can not be accessed directly outside,

                       It does not provide any way to modify the state from the outside

  3, states with certainty: the change from the initial state (pending) for the implementation of successful (fulfilled) or fails (rejected),

                     Then the status is determined completely down, will not be affected by any subsequent operation

  4, the callback function is a one-time: up to trigger once, to avoid the problem in the past based on asynchronous programming callback functions among the callback function to perform the number of uncontrolled

  5, there is no callback premature question: If the callback function is registered in the state before the change is triggered when changing state will wait; when the registration status has been determined,

                         Promise you'll call this function immediately and pass the corresponding return value

  6, between the callback function does not affect each other: the isolation of the Promise with a registered callback function with each other,

                           Therefore, individual callback execution error will not affect the normal execution of other callback functions

  7, the timing of the implementation of the callback function is determined

 

Promise Serial execution and chained calls:

  1、Promise.prototype.then:

    (. 1) .then (onFulfilled, onRejected)  is the prototype chain Promise method for registration when the state of the object changes Promise callback

    (2) It takes two callback functions as parameters , respectively, when the trigger is in a different state changes Promise, which may default to onRejected

    (3) .then () method creates and returns a new Promise objects (with p2 refer to the current object with the Promise listening to refer p1),

       Is used to characterize the implementation of the callback function, the process satisfies the following rules:

        a, p1 state only determines when to perform the callback and executing that type of callback, and does not affect the state p2

        b, p2 initial state is 'pending', when the callback function executes a success status is changed to 'fulfilled',

           If an exception is thrown during the execution of the callback is changed to 'rejected'

        c, the callback function's return value as the value of the parameter p2 trigger state changes resolve (value) when passing it down

  2, Promise chain call:

    (1) a plurality of very intuitive need to be a top-down process performed by an asynchronous sequential linear combination manner,

       While reducing coding difficulty, but also increases the readability of the code

    (2) based on the registration in the same callback object Promise each other without disturbing each other characteristics, we can chain bifurcation in wherever needed

  3, Promise and parallel execution management:

    (1) is performed based on Promise serial asynchronous task, essentially to an asynchronous control tasks .then () method

       Then trigger the next task after the completion of an asynchronous

    (2) only needs to create an asynchronous synchronization with these tasks , and their corresponding management Promise objects can be transformed into parallel execution

function getX() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(1)
        }, 3000)
    })
}

function getY() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(10)
        }, 5000)
    })
}

function getXAndY([promiseX, promiseY]) {
    let results = []
    return promiseX
        .then(x => {
            results.push(x)
            return promiseY
        })
        .then(y => {
            results.push(y)
            return results
        })
}

getXAndY([
    getX(),
    getY()
])
    .then(results => {
        // 5s 后输出 11
        console.log(results[0] + results[1])
    })

    (3)Promise 已经提供了 Promise.all() 方法来实现与上述 getXAndY 一样的功能(一种并行状态管理的方案)

    (4)Promise.race() 方法,用于获取第一个发生状态变更的 Promise 对象

 

Fetch API:

  1、Fetch API 首先提供了网络请求相关的方法 fetch(),其次还提供了用于描述资源请求的 Request 类,以及描述

     资源响应的 Response 对象,这样就能够以一种统一的形式将资源的请求与响应过程应用到更多的场景当中

  2、fetch() 需要传入一个 Request 对象作为参数,它会根据 Request 对象所描述的请求信息发起网络请求

  3、fetch() 还支持传入请求 URL 和请求配置项的方式,它会自动根据这些参数实例化 Request 对象之后再去发起请求

fetch(new Request('/path/to/resource', {method: 'GET'}))
// 等价于
fetch('/path/to/resource', {method: 'GET'})

  4、fetch() 会返回 Promise 对象,当请求响应时 Promise 执行 resolve 并传回 Response 对象

  5、fetch() 只有在网络错误或者是请求中断的时候才会抛出异常,此时 Promise 对象会执行 reject 并返回错误信息,

     而服务端返回的 HTTP 404、500 等状态码并不认为是网络错误,需要检查 Response.status、Response.ok

     等属性以确保请求成功响应

fetch('/path/to/resource').then(response => {
  if (response.status === 200) {
    // 请求成功
  } else {
    // 请求失败
  }
})
.catch(err => {
  // 网络请求失败或请求被中断
})

 

Request:

  1、Request 是一个用于描述资源请求的类,通过 Request() 构造函数可以实例化一个 Request 对象

  2、语法格式:let request = new Request(input, init)

注:input 代表想要请求的资源,可以是资源的 URL,或者是描述资源请求的 Reqeust 对象;

    init 为可选参数,可以用来定义请求中的其他选项

  3、发送请求:

    (1)GET 请求,请求参数需要写到 URL 当中

    (2)POST 请求,请求参数需要写到 body 当中

    (3)自定义请求的 Headers 信息

    (4)设置发起资源请求时带上 cookie

// GET 请求
let getRequest = new Request('requestUrl?name=lilei', {
    method: 'GET'
})

// POST 请求
let postRequest = new Request('requestUrl', {
    method: 'POST',
    // body 可以是 Blob、FormData、字符串等等
    body: JSON.stringify({
        name: 'lilei'
    })
})

// 自定义请求的 Headers 信息
let customRequest = new Request('requestUrl', {
    // 这里展示请求 Content-Type 为 text/plain 的资源
    headers: new Headers({
        'Content-Type': 'text/plain'
    })
})

  4、常见属性:

    (1)url:String 类型,只读,请求的 url

    (2)method:String 类型,只读,请求的方法,如 'GET','POST' 等

    (3)headers:Headers 类型,只读,请求的头部,可通过 get() 方法获取 'Content-Type','User-Agent' 等信息

//设置发起资源请求时带上 cookie
let cookieRequest = new Request('requestUrl', {
    credentials: 'include'
})

if (request.url === 'https://example.com/data.txt') {
    // ...
}
if (request.method === 'POST') {
    // ...
}
if (reuqest.headers.get('Content-Type') === 'text/html') {
    // ...
}
 

Response:

  1、Response 类用于描述请求响应数据,通过 Response() 构造函数可以实例化一个 Response 对象

  2、语法格式:let response = new Response(body, init)

注:body 参数代表请求响应的资源内容,可以是字符串、FormData、Blob 等等;

    init 为可选参数对象,可用来设置响应的 status、statusText、headers 等内容

  3、在实际应用当中,我们一般会通过 fetch()、Cache API 等等获得请求响应对象,然后再对响应对象进行操作

  4、Response 对象的相关属性:

    (1)status:Number 类型,包含了 Response 的状态码信息,开发者可以直接通过 status 属性进行状态码检查,

       从而排除服务端返回的错误响应

    (2)statusText:String 类型,包含了与状态码一致的状态信息,一般用于解释状态码的具体含义

    (3)ok:Boolean 类型,只有当状态码在 200-299 的范围时,ok 的值为 true

  5、读取响应体:

    (1)text():解析为字符串

    (2)json():解析为 JSON 对象

    (3)blob():解析为 Blob 对象

    (4)formData():解析为 FormData 对象

    (5)arrayBuffer():解析为 ArrayBuffer 对象

  6、Response 提供了 clone() 方法来实现对 Response 对象的拷贝

 

Fetch API 与 XHR 对比:

  1、Fetch API 的异步机制更为先进

  2、Fetch API 更为简洁

  3、Fetch API 的应用范围更广

 

Cache API:

  1、兼容性检测:在主线程或者 Worker 线程中通过判断全局变量 caches 是否存在来检测浏览器是否支持 Cache API

if ('caches' in self) {
    console.log('当前环境支持 Cache API')
}

  2、打开 Cache 对象:通过 caches.open() 方法可以打开一个 Cache 对象,cacheName 表示要打开的 Cache 对象的名称。

                      该方法是异步方法,返回的 Promise 对象在 resolve 时会返回成功打开的 Cache 对象

caches.open(cacheName).then(cache => {/* 获得 Cache 对象 */})

  3、添加缓存:Cache 对象提供了 put()、add()、addAll() 三个方法来添加或者覆盖资源请求响应的缓存

               这些添加缓存的方法只会对 GET 请求起作用

  4、查找缓存:cache.match() 和 cache.matchAll() 可以实现对缓存的查找

  5、获取匹配的请求:通过 cache.keys() 方法实现

  6、删除缓存:通过 cache.delete() 方法可以实现对缓存的清理

Guess you like

Origin www.cnblogs.com/lemonyam/p/11938433.html
Recommended