劉杰
    • 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
    # Async JS Crash Course ###### tags: `Javascript` # 使用範例來理解Async JS在什麼情況下適合作用: * 取得post貼上DOM延遲一秒鐘 * 創造新的post花了兩秒鐘 這樣會發生什麼情況? ![](https://i.imgur.com/lW6aV3a.png) DOM會先PO post上去不等新的post創造好,所以永遠更新不到新的post ```javascript= const posts = [{ title: 'Post One', body: 'This is post one' }, { title: 'Post Two', body: 'This is post two' }, ]; // 把取得的post貼到DOM上面 延遲一秒鐘 function getPost() { setTimeout(() => { let output = ''; posts.forEach((post, index) => { output += `<li>${post.title}</li>`; }); document.body.innerHTML = output; }, 1000); } //創造一個新的post丟上去花了兩秒鐘 function createPost(post) { setTimeout(() => { posts.push(post); }, 2000); } getPost(); createPost({ title: 'Post Three', body: 'This is post Three' }); ``` # 使用callback: 使用callback代表getPosts,這樣一來就會在創造好新的post之後才會觸發getPosts整個過程會在兩秒內完成 需要注意callback的寫法在呼叫函式的部分撰寫的callback不需要加上()要特別留意 ```javascript= //創造一個新的post丟上去花了兩秒鐘 //這邊的callback就代表了getPosts所以必須等創造好了新的post之後 // getPost才會觸發也才會把取的的物件推上去DOM所以就可以顯示新的post搂! function createPost(post, callback) { setTimeout(() => { posts.push(post); callback(); }, 2000); } createPost({ title: 'Post Three', body: 'This is post Three' }, getPosts) ``` # 使用promise: * promise解決會呼叫resolve * promise錯誤則呼叫reject promise成功則會使用then()內部的函式順利的印出新的post ![](https://i.imgur.com/Vc1kOWO.png) promise失敗(改寫error變數成true)則會顯示錯誤訊息在console裡面 也可以使用`catch`方法抓取錯誤的內容 ![](https://i.imgur.com/s18nYiL.png) ```javascript= function createPost(post, ) { //如果promise解決會呼叫resolve //如果promise錯誤則呼叫reject return new Promise((resolve, reject) => { setTimeout(() => { posts.push(post); // 解釋promise內部的兩個參數的判斷是如何運作 const error = false; if (!error) { resolve(); } else { reject('Error: something went wrong'); } }, 2000); }); } createPost({ title: 'Post Three', body: 'This is post three' }).then(getPosts).catch(err => console.log(err)); ``` ## 示範promise.all 常常promise會不只一個,一個一個接then太累了,所以可以使用promise.all一次抓住一同使用.then就好瞜! ```javascript= const promise1 = Promise.resolve('hello world'); const promise2 = 10; const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 2000, 'Goodbye')); Promise.all([promise1, promise2, promise3]).then(values => console.log(values)); ``` 最後.then的印出結果 ![](https://i.imgur.com/9yQSz0L.png) ## 示範fetch API 相關的promise寫法 使用fetch抓取資料的話必須轉化格式所以在指派給變數的階段就要先.then轉換格式 這樣才可以在promise.all的階段被真正抓取到資料 ```javascript= //使用兩個.then因為要轉換JSON格式 const promise4 = fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json()); Promise.all([promise1, promise2, promise3, promise4]).then(values => console.log(values)); ``` 最後.then的印出結果 ![](https://i.imgur.com/8fI5g5T.png) ## 使用async: `await` 等待一個同步的過程或動作去完成後才去執行其他動作 等待createPost處理完內部的函式createPost後也就是創造新的post後,才會往getPosts去執行這樣就會顯示摟! ```javascript= function createPost(post, ) { return new Promise((resolve, reject) => { setTimeout(() => { posts.push(post); const error = false; if (!error) { resolve(); } else { reject('Error: something went wrong'); } }, 2000); }); } // 等待createPost處理完成後,才會往getPosts去執行 async function init() { await createPost({ title: 'Post Three', body: 'This is post three' }); getPosts(); } init(); ``` ## 示範fetch API 相關的async寫法 不用.then一切都更乾淨好讀 一樣fetch都需要資料轉換,但是這邊重新指派一個變數處理比較特別 ```javascript= async function fetchUsers() { const res = await fetch('https://jsonplaceholder.typicode.com/users'); const data = await res.json(); console.log(data); } fetchUsers(); ``` fetch的資料印出: ![](https://i.imgur.com/Xc4q0xs.png)

    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