RZ-Huang
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Fetch & Promise ###### tags: `javascript` ## Fetch 新時代的 XMLHttpRequest ### 用法 ``` <script> fetch('https://jsonplaceholder.typicode.com/posts/1') .then(function(res) { console.log(res) }) </script> ``` 在 `fetch()` 中加入要連接的 API 網址,接著後面加上的 `then()` 放入 callback function,`res`參數即是 API 傳回來的結果,而這個結果是一個物件。 ``` <script> fetch('https://jsonplaceholder.typicode.com/posts/1') .then(function(res) { return res.json() }) .then(function(result) { console.log(result) }) </script> ``` 在 `res` 參數中,有個`json`的方法可以把傳回來的結果轉為 json 格式;如果是使用`text`的方法則是把傳回來的結果轉為純文字格式。 另外 `then` 的方法可以接到上一個方法的 `return` 值,因此上面的例子的 `result` 會收到 `res.json()` 的結果。 ``` <script> fetch('https://jsonplaceholder.typicode.com/posts/1') .then(function(res) { return res.json() }) .then(function(result) { console.log(result) }) .catch(function(err) { console.log(err) }) </script> ``` `catch`的方法用在當使用 `fetch` 傳送資料時若有誤,則印出錯誤的訊息。 ## Promise 當在使用 ajax 或是 EventListener 的時候,其實都有用到 promise 的機制。 像是上面的 `fetch()` 傳回來的結果就是個 `promise` 的物件。也因為 `promise`的特性可以讓我們對`promise`傳回來的結果繼續使用其它的方法,而每個方法回傳的結果也都會是個`promise`,所以說每個方法所拿到的結果都會是上面的`promise`產生的結果。 ### 產生 Promise ``` const api = new Promise(function(resolve, reject){ resolve('123') }) api.then(result => { console.log(result) }) ``` 實務上可以產生一個 Promise 的物件,把要做為非同步的事情都包在裡面,callback function 的第一個參數`resolve`回傳的是當成功抓取資料就會做的事情,第二個參數`reject`則是當失敗的時候會做的事情。 而 Promise 產生後的物件指派一個變數後,藉由這個變數就跟使用`fetch()`一樣,可以使用`then`與`catch`的方法。上面的例子的`result`結果會是`resolve('123')`回傳的`123`字串。 ``` const api = new Promise(function(resolve, reject){ reject('dsf') }) api.then(result => { console.log(result) }).catch(err => { console.log(err) }) ``` 上面的`reject('sdf')`則是當錯誤的時候會回傳`sdf`的字串到`catch`的方法裡面。 ----- 使用 Promise 的好處就是大家要使用 callback function 作為非同步的函式時,可以有個統一的規格去依循,而不是依照每個人各自的門派,也就是說,`Promise`就是有個標準化的物件可以給予我們使用。 ### 使用 setTimeout() 做非同步 ``` const sleep = new Promise(function(resolve, reject){ setTimeout( () => { resolve('sleep 3 seconds') }, 3000) }) sleep.then(result => { console.log(result) }).catch(err => { console.log(err) }) ``` 藉由 `setTimeout()` 定時器就可以設定延遲時間,時間一到才會執行 Promise 的 function,達到一個非同步的效果。 ### XMLHttpRequest 包在 Promise 裡面 ``` const getPosts = new Promise(function(resolve, reject){ const request = new XMLHttpRequest(); request.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { resolve(request.responseText); } }; request.send(); }) getPosts.then(result => { console.log(result) }).catch(err => { console.log(err) }) ``` 把 `XMLHttpRequest` 的用法包在 `Promise` 裡面就可以使用 `Promise` 的機制與方法。 ``` const get = url => new Promise((resolve, reject) => { const request = new XMLHttpRequest(); request.open("GET", url, true); request.onreadystatechange = () => { if (request.readyState == 4 && request.status == 200) { resolve(request.responseText); } }; request.send(); }) get("https://jsonplaceholder.typicode.com/posts/1").then(result => { console.log(result) }).catch(err => { console.log(err) }) ``` 我們可以把 `Prmoise` 的物件直接用一個 function 包住,參數若是 API 的網址,那麼這個 function 的用法就和直接使用 `fetch` 一樣,如上方第二段的程式碼:`get("https://jsonplaceholder.typicode.com/posts/1").then()`,把它換成`fetch("https://jsonplaceholder.typicode.com/posts/1").then()`結果會是一樣的。 ### Promise 的三個狀態 #### Pending 尚未做任何動作時的狀態。 #### Fulfilled 當 `Promise` 被呼叫時的狀態。 #### Rejected 當 `Prmoise` 的 `reject` 被呼叫的狀態。 ### Promise.all 【待了解】 #### 延伸資料 1. [鐵人賽:ES6 原生 Fetch 遠端資料方法](https://wcc723.github.io/javascript/2017/12/28/javascript-fetch/) 2. [使用 Fetch](https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully