U1320100568 / Mvc-third

0 stars 1 forks source link

Fetch / Promise / Async / Await 簡述 #4

Open U1320100568 opened 6 years ago

U1320100568 commented 6 years ago

Fetch (HTML5)

https://notfalse.net/29/XMLHttpRequest#jsonHandler https://eyesofkids.gitbooks.io/javascript-start-from-es6/content/part4/ajax_fetch.html 可以取代Xhr 的語法,結構是 promise 語法(.fail .done),類似jquery 語法 和jquery最大不同是:

  1. jquery 底層還是xhr,fetch是原生html
  2. fetch狀態錯誤還是會resolve,但可用ok屬性來判斷,只有網路故障才會reject
  3. 預設不會傳送或接收cookie
  4. 依照回傳類型,選擇response解析類型
  5. request、response可以變成物件重複使用,也可以微調

fetch主要物件GlobalFetch、Request、Response、Headers、Body request response 都有 header 和 body的實作, fetch也不一定要傳入實體

fetch('./sample.json', {
    method: 'GET',
    mode: 'cors',
    redirect: 'follow',
    headers: new Headers({
        'Content-Type': 'text/json'
    })

fetch( ).then( )會回傳promise物件 response回來的內容是body物件 (ReadableStream 物件) 要依照不同的資料類型的解析方法 (.text() .json() ...) 會得到一個解析完的pormise,所以通常會在then才得到值

fetch('http...').then(function(response) {
    return response.json()
}).then(function(j) {
    console.log(j)
}).catch(function(err) {
})

若要傳送object要先stringify,header的 Content-Type :'application/json' (對應)

U1320100568 commented 6 years ago

Async / Await (ES7)

用一個非同步函式 ,用 await 等待 promise物件解析

async function test(param) {
    // await 會暫停此 async function 的執行,
    // 並等待 doSomethingAsync() 回傳 Promise 解析 (Resolved) 的 『值 (Value)』
    // 若 Promise 解析失敗 (被拒絕 rejected) 則拋出例外,並附加 『拒絕理由 (reason) 』
    var data = await doSomethingAsync();

    // Promise 解析完成之後,會繼續此 async function 的執行
    console.log(data);
}

可以使用 await 等待 ajax 回傳的 promise 物件 await 後處理 resolved 後的程式,或是 catch 去抓reject的狀態 不用在ajax後處理resolve reject callback

async function ajax(setting) {
    try {
        var data = await $.ajax(setting);
       success 後要幹嘛
    } catch (jqXHR) {
        console.error(jqXHR.statusText); // reject要幹嘛
    }
}
ajax(setting);
U1320100568 commented 6 years ago

Promise (ES6)

是一個非同步的操作結果,根據非同步的狀態執行不同的結果(ex . resolved -> done / then ) 在jquery 的ajax jqXhr 中就是promise promise 可以在單個 request 指定多個callback,也可以在完成後指派多個callback

U1320100568 commented 6 years ago

fetch post 範本

fetch("@Url.Action("RoleModifiedFeatures")",
{
            method: 'post',
           body: JSON.stringify({
               roleId: roleid,
               featureId: $(this).data("featid")
            }),
           headers: {
               'Content-Type':'application/json'
           }
} )
.then(function (response) {
             return response.json();
 })
 .then(function (result){
             console.log(result);
})
 .catch(function (err) {
             console.log("err: " + err);
 });
[HttpPost]
public ActionResult RoleModifiedFeatures(int roleId, int? roleFeatureId, int? featureId)
{
        return Json(new { roleId = roleFeat.RoleFeat.RoleId, roleFeatNum = roleFeat.RoleFeat.RFNum, featId = roleFeat.RoleFeat.FeatureId, featName = roleFeat.FeatName }, JsonRequestBehavior.AllowGet);
}
U1320100568 commented 6 years ago

Fetch 主要介面(物件)

GlobalFetch:fetch( ) Request:method、url、headers、context、body屬性,clone方法 Response;headers、ok、status、statusText、type、body屬性,clone方法 Headers:request、response裡面header 的設定 Body:在request、response裡面的主體內容資料

Fetch Response

readableStream 可解析方法類型 text 、json、arrayBuffer、formData、blob text ():純文字HTML json ():json格式回傳是promise物件 blob ():raw data可用於圖片、檔案 formData () :傳送post 表單form arrayBuffer () :