Erica Du
    • 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 No publishing access yet

      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.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      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 New
    • Engagement control
    • Make a copy
    • 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 Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy 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 No publishing access yet

    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.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Promise ## 什麼是 Promise Promise 是 ES6 新增的語法,用來優化非同步取得遠端資料的方法,可以解決 AJAX 的非同步問題,同時增加可讀性。 * 常見例如 Axios、Fetch --- ## 為什麼需要 Promise * JavaScript 是屬於同步的程式語言,因此一次僅能做一件事情 * 遇到非同步的事件時,就會將非同步的事件移動到程式碼的最後方,等到所有的原始碼運行完以後才會執行非同步的事件 ```javascript= console.log('開始') // 執行順序 1 setTimeout(() => { console.log('非同步事件') // 執行順序 3 }, 0) console.log('程式碼結束') // 執行順序 2 ``` 而 Ajax 也是屬於非同步行為,當需要 **確保擷取到遠端資料才繼續往下執行時**,如果程式碼是依序撰寫的方式,就會無法正確呈現資料 --- ## 建立 Promise * 因為 Promise 是建構函式,如果需要呼叫其中的原型方法:`then`、`catch`、`finally`,則必須透過 `new Promise()` 建立新物件才能使用 * Promise 建構函式建立時,必須傳入一個函式作為參數,此函式的參數包含 `resolve`(成功訊息), `reject`(失敗訊息) * `resolve` 及 `reject` 的名稱可以自訂,但避免混淆,還是習慣維持預設名稱 ```javascript= function promise(num) { return new Promise((resolve, reject) => { num ? resolve(`${num}, 成功`) : reject('失敗') }) } ``` ### 狀態 Promise 在處理非同步的事件的過程中,包含不同的進度狀態 * Pending:尚未得到結果 * Resolved:事件已經執行完畢且成功操作,回傳 `resolve` 的結果 * Rejected:事件已經執行完畢但操作失敗,回傳 `reject` 的結果 ![](https://i.imgur.com/oAg5u0H.png =700x) ### 接收回傳 Promise 可以用 `then` 和 `catch` 來接收並回傳結果: `then` 可以同時接收成功、失敗結果,而 `catch` 只接收失敗結果 * **使用 catch 接收失敗:** 在任何階段遇到 `reject` 時,都會直接跳到 `catch`,之後的 `then` 都不會執行 雖然 `catch` 依然可以使用 `return` 繼續串接,但很少這樣使用 ```javascript= promise(1) .then(success => { console.log(success) // resolve 接收成功 // '1' return promise(0) // return promise(0) -> reject 跳到 catch }) .then(success => { // 因為上面出現 reject 所以跳過 console.log(success) return promise(3) }) .catch( fail => { console.log(fail) // reject 接收失敗 // '失敗' }) ``` * **使用 then 接收失敗:** `then` 中的兩個函式必定執行其中一個,可以用此方式確保所有的鏈接都能夠被執行 ```javascript= promise(0) .then(success => { console.log(success) return promise(1) }, fail => { console.log(fail) // reject 接收失敗 // '失敗' return promise(2) // return promise(2) }) .then(success => { console.log(success) // resolve 接收成功 // '2' return promise(0) // return promise(0) }, fail => { console.log(fail) return promise(4) }) .then(success => { console.log(success) }, fail => { console.log(fail) // reject 接收失敗 // '失敗' }) ``` ### 完成 * 最後可以使用 `finally` 來確認工作結束 * `finally` 不帶有任何參數,適合用來確認 Ajax 已經讀取完成 ```javascript= promise(1) .then(success => { console.log(success) }).finally(() => { console.log('done') }) ``` --- ## Promise 方法 **Promise.all** * 透過陣列的形式傳入多個 promise 函式 * 在全部執行完成後回傳陣列結果 * 陣列的結果順序與一開始傳入的一致 * 適合用在多支 API 要一起執行,並確保全部完成後才進行其他工作 ```javascript= Promise.all([promise(1), promise(2), promise(3)]) .then(res => { console.log(res) // ["1", "2", "3"] }) ``` **Promise.race** * 多個 Promise 同時執行,但僅回傳第一個完成的結果 ```javascript= Promise.race([promise(1), promise(2), promise(3)]) .then(res => { console.log(res) // "1" }) ``` **Promise.reject、Promise.resolve** * 直接定義 Promise 物件已經完成的狀態(resolve, reject) * 與 `new Promise` 一樣會產生一個新的 Promise 物件,但結果是已經確定的 * `Promise.resolve` 直接定義 `resolve`,但無法取得失敗結果 * `Promise.reject` 直接定義 `reject`,但無法取得成功結果 --- ## Promise 和 XMLHttpRequest **使用 XHR 處理 Ajax:** * 透過 `XMLHttpRequest` 建構式來產生進行遠端請求的物件 * 依序定義方法 `GET` 及狀態 `onload` 並送出請求 `send` * 取得結果後的其它行為則需要撰寫在 `onload` 內 ```javascript= const url = 'http://API網址' const xhr = new XMLHttpRequest() // 定義 Http xhruest xhr.open('GET', url) // 定義方法 xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded') xhr.onload = () => { // 當請求完成,執行函式 if (xhr.status == 200) { console.log(xhr.response) // 成功時列出結果 } else { console.log('fail') } } xhr.send() // 送出請求 ``` **使用 Promise 處理 Ajax:** * 將上面的內容直接用 `new Promise()` 封裝進 `getData` 的函式內 * 之後的 HTTP 就能直接透過 `getData` 函式取得 * 重複運用的情況下程式碼可以大幅提高易讀性 ```javascript= const url = 'http://API網址' const getData = (url) => { return new Promise( (resolve, reject) => { const xhr = new XMLHttpRequest() xhr.open('GET', url) xhr.onload = () => { if (xhr.status == 200) { resolve(JSON.parse(xhr.response)) // 使用 resolve 回傳成功結果 // 也可以在此直接轉換成 JSON 格式 } else { reject(new Error(xhr)) // 使用 reject 自訂失敗結果 } } xhr.send() }) } getData(url) .then( res => { console.log(res) }) .catch( err => { console.log(err) }) ``` --- ## Fetch **使用 Fetch 處理 Ajax:** * fetch 會使用 ES6 的 Promise 作回應 (`then`、`catch`) * 回傳的資料為 `ReadableStream` 物件,需要使用不同資料類型對應方法,才能正確取得資料物件 ```javascript= const url = 'http://API網址' fetch(url) .then( res => { console.log(res) return res.json() // 將資料轉成 json 格式 }) .then( res => { console.log(res) }) .catch( err => { console.log(err) }) ``` **ReadableStream** [MDN說明](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) `ReadableStream` 為 API 接口,預設 `locked` 唯讀,需透過對應的方法來取得資料: * `text()` * `json()` * `formData()` * `blob()` * `arrayBuffer()` **blob()** 將資料轉為 `blob` 物件,像是圖片就可以做這樣的轉換 (這裡的圖片並非指圖片路徑,而是圖片檔案本身) ```javascript= let imgUrl = 'https://images.unsplash.com/photo-1472157592780-9e5265f17f8f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=600&q=100' // unsplash 圖片網址 fetch(imgUrl) .then((response) => { return response.blob() // 資料轉成圖片物件 }) .then((imageBlob) => { let img = document.createElement('IMG') document.body.appendChild(img) img.src = URL.createObjectURL(imageBlob) // 將 blob 物件轉為 url }) ``` --- ## ES7 async await 在 ES7 裡頭 async 的本質是 promise 的語法糖,只要 function 標記為 async,就表示裡頭可以撰寫 await 的同步語法,而 await 顧名思義就是「等待」,它會確保一個 promise 物件都解決 ( resolve ) 或出錯 ( reject ) 後才會進行下一步。 [ 簡單理解 JavaScript Async 和 Await](https://www.oxxostudio.tw/articles/201908/js-async-await.html) --- ## 範例連結 * [CodePen](https://codepen.io/kaoru44689/pen/PoZMKrq) --- ## 參考文章 * [JavaScript Promise 全介紹](https://wcc723.github.io/development/2020/02/16/all-new-promise/) * [淺談JavaScript ES6入門Part2-類別、物件與建構式](https://medium.com/@brianwu291/learn-basic-javascript-es6-part2-d8fe175107c3) * [從Promise開始的JavaScript異步生活](https://eyesofkids.gitbooks.io/javascript-start-es6-promise/content/) * [ES6 Fetch 遠端資料方法](https://ithelp.ithome.com.tw/articles/10194388) * [JavaScript Fetch API 使用教學](https://www.oxxostudio.tw/articles/201908/js-fetch.html)

    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
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    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