Promise object可以帶入一個函式,代表要給予承諾的程式

Posted in :

這個promise object 很常可以看到, 在別人的 javascript source code 裡, 應該是要必學的技術之一. 今天是先看到一則新聞:

Safari漏洞或導致瀏覽歷史、Google帳戶資訊外洩
https://chinese.engadget.com/safari-webkit-exploit-browser-history-google-account-010041068.html

文章重點之一:

問題的根源,在於Apple違背了IndexedDB框架(在許多瀏覽器中都承擔儲存數據的任務)的同源原則。

所以我查了一下什麼是 IndexedDB, 順便研究一下

[Day15] 使用indexedDB暫存Dynamic Data(Part2)
https://ithelp.ithome.com.tw/articles/10222545

上面這個人寫的滿好的, 順便研究一下他其他相關內容在寫麼, 就看到這篇:

[Day06] 複習一下Jacvascript中的 Promise 和 Fetch(Part1)
https://ithelp.ithome.com.tw/articles/10217932

使用他給的範例:

console.log('Hi');

var promise = new Promise(function(resolve, reject) {
    setTimeout(function cb() {
        reject({code: 500, message: 'An error occur'});
    }, 2000);
});

promise.then(function(result) {
    console.log("result:");
    console.log(result);
}).catch(function(err) {
    console.log("err:");
    console.log(err);
});

console.log('Everybody');

電腦執行結果:

感覺 promise 很有趣.


Fetch API是目前較新版本的瀏覽器都有支援的javascript function,它允許我們透過HTTP Request來獲取外部資源,跟Ajax功能類似,使用fetch其實比Ajax還要好一些,因為可以使用離線的快取。

fetch是一個非同步的函式,會回傳一個promise object。

fetch get example:

fetch('https://httpbin.org/ip',).then(function(response) {
    console.log(response);
    return response.json();
}).then(function(data) {
    console.log(data);
}).catch(function(err) {
    console.log(err);
});

fetch post example:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    mode: "cors",
    body: JSON.stringify({message: 'Does it work?'})
}).then(function(response) {
    console.log(response);
    return response.json();
}).then(function(data) {
    console.log(data);
}).catch(function(err) {
    console.log(err);
});

See fetch() for the full options available, and more details.

// Example POST method implementation:
async function postData(url = "", data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, *cors, same-origin
    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, *same-origin, omit
    headers: {
      "Content-Type": "application/json",
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: "follow", // manual, *follow, error
    referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data), // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData("https://example.com/answer", { answer: 42 }).then((data) => {
  console.log(data); // JSON data parsed by `data.json()` call
});

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *