grayshine
    • 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
    # <font class="h2">Promise物件</font> ###### tags: `javascript` <style> .h2 { background: linear-gradient(135deg,#fff,#537479) ; color: #537479; display:block; padding: 6px 5px; border-radius: 4px; } .h3 { background: linear-gradient(180deg,#fff 50%,#c9d5d4) ; color: #537479; display:block; padding: 6px 5px; border-bottom: 3px solid #537479; } .h4 { color: #537479; font-weight:bold; font-size:1.1em; } </style> <br> ### <font class="h3">解決非同步的方法</font> 1. 回呼函示(早期) 2. Promise物件(es6) 3. Async/Await(es6) <br> :::info 語法: ```javascript new Promise(執行程式){成功程序,失敗程序} .then(()=>{成功時的動作}) .catch(()=>{失敗時的動作}) .finally(()=>{無論如何都會執行}) ``` ::: ![](https://i.imgur.com/CFn8zyM.png) ![](https://i.imgur.com/lkKRfui.png) <br> ![](https://i.imgur.com/etimJ58.png) <br><br><br><br> ```javascript function mix(){ console.log(1) setTimeout(()=>{console.log(2)},0) console.log(3) console.log(4) } mix() //1342 ``` <br><br> ### callback解決非同步: ```javascript function mix() { console.log(1) } function second(callback) { setTimeout(() => { console.log(2) callback() }, 0) } function third() { console.log(3) console.log(4) } mix() second(third) ``` <br><br> ### promise解決非同步: ```javascript let def = new Promise((resolve, reject) => { setTimeout(() => { resolve(2) }, 0); }) function mix() { console.log(1) def.then((res) => { console.log(res) }).then(() => { console.log(3) console.log(4) }) } mix() ``` <br><br><br><br> ### <font class="h3">範例</font> ```javascript function add(n1, n2){ return n1+n2; } function test(){ let result = add(3,4); console.log(result); } test()//7 ``` <br><br> ### 非同步範例: ![](https://i.imgur.com/s9xdb7v.png) return基本上失效了,印出結果是undefined <br> ### <font class="h4">使用promise 範例1.</font> ![](https://i.imgur.com/S8NK4zE.png) <br> 可以這樣調整,比較常見是這樣寫,用return將Promise物件回傳 ![](https://i.imgur.com/dG5YDwN.png) <br> ### resolve、reject參數 ![](https://i.imgur.com/4dFpLgT.png) 呼叫resolve會對應到then,如果呼叫reject會對應到catch <br><br><br><br> ### <font class="h4">➤ promise 範例2.</font> ```javascript function promiseFn(num,time = 500){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ if(num){ resolve(`成功${num}`) }else{ reject('失敗') } },time) }) } promiseFn(1,2000) .then(res =>{ console.log(res) }) ``` <br><br><br><br> ### <font class="h4">➤ promise 範例3.</font> ![](https://i.imgur.com/91Z3mzJ.png) <br><br><br><br> ### <font class="h4">➤ 範例:resolve也可以回傳失敗</font> ![](https://i.imgur.com/eX5KTNT.png) <br><br><br><br> ### <font class="h4">➤多個promise任務範例:</font> ```javascript function delayedAdd(n1, n2, delayTime){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ resolve(n1+n2); },delayTime); }); } function test(){ let promise1 = delayedAdd(3,4,2000); let promise2 = delayedAdd(2,3,3000); //多個Promise 都完成之後,才繼續工作 Promise.all([promise1,promise2]).then(function(results){ console.log(results);//[7,5] }); } test() ``` `Promise.all`的`Promise`要大寫 <br><br><br><br> ### <font class="h4">➤多個promise任務做相乘範例:</font> ```javascript function delayedAdd(n1, n2, delayTime){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ resolve(n1+n2); },delayTime); }); } function test(){ let promise1 = delayedAdd(3,4,2000); let promise2 = delayedAdd(2,3,3000); //多個Promise 都完成之後,才繼續工作 Promise.all([promise1,promise2]).then(function(results){ let answer = results.reduce(function(total,value){ return total*value; }) console.log(answer);//35 }); } test() ``` <br><br><br><br> ### <font class="h3">Ajax方面</font> ### <font class="h4">➤Ajax使用Promise 範例:</font> :bulb:這裡使用的是JavaScript原生寫法「XMLHttpRequest」 ```javascript function getData() { let req = new XMLHttpRequest() req.open("get", "https://training.pada-x.com/resources/javascript-es6-react/data.out") req.onload = function () { alert(this.responseText) } req.send() } getData(); ``` ### 使用then回傳連線失敗範例: ![](https://i.imgur.com/sGQISxR.png) <br> ### 使用catch回傳連線失敗範例: ```javascript function getData() { return new Promise(function(resolve,reject){ let req = new XMLHttpRequest() req.open("get", "https://training.pada-x.com/resources/javascript-es6-react/data.out") req.onload = function(){ resolve(this.responseText) }; req.onerror=function(){ reject("Error") } req.send() }) } let promise=getData(); promise.then(function(result){ alert(result) }).catch(function(err){ alert(err) }) ``` <br><br><br><br> ### <font class="h4">➤Ajax使用Promise 範例2:</font> ```javascript const url = 'https://randomuser.me/api' Promise.all([axios.get(url),axios.get(url)]) .then(([res1,res2])=>{ console.log(res1,res2) }) ``` ![](https://i.imgur.com/v4NjTgN.png) <br><br><br><br> ### <font class="h4">➤Ajax使用Promise 範例3:</font> ```javascript const url = 'https://randomuser.me/api' let data = {}; axios.get(url) .then( res => { data = res }) console.log(data) //{} ``` 這裡因為非同步的關係,data會是空物件 ```javascript const url = 'https://randomuser.me/api' let data = {}; function getData(){ return new Promise((resolve,reject)=>{ axios.get(url) .then( res => { resolve(res) }) }) } getData().then(res=>{ data = res console.log(data) }) ``` <br><br><br><br> ### <font class="h3">多個Promise執行順序方面 (鏈接技巧)Promise chain</font> ==鏈接可以避免巢狀結構== ### <font class="h4">➤範例1:</font> ```javascript function promiseFn(num){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ if(num){ resolve(`成功${num}`) }else{ reject('失敗') } },0) }) } promiseFn(1) .then(res =>{ console.log(res) return promiseFn(2) }) .then(res =>{ console.log(res) return promiseFn(3) }) .then(res =>{ console.log(res) }) .catch(res =>{ console.log('catch',res) }) //成功1 成功2 成功3 ``` <br><br><br> ### <font class="h4">➤範例2:</font> ```javascript function funcA(){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ console.log('A'); resolve('A'); },(Math.random()+1)*1000) }) } function funcB(){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ console.log('B'); resolve('B'); },(Math.random()+1)*1000) }) } function funcC(){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ console.log('C'); resolve('C'); },(Math.random()+1)*1000) }) } funcA().then(funcB).then(funcC) ``` 這樣就可以做到等funcA()被「resolve」之後再執行funcB(),然後resolve再執行funcC()的順序了。 <br><br><br> ### <font class="h4">➤範例3: 使用return做promise額外請求串接</font> ![](https://i.imgur.com/f0xok5T.png) <br><br><br> ### 使用Promise.all 如果不在乎funcA()、funcB()、funcC()誰先誰後的話,就就可以使用Promise.all ```javascript function funcA(){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ console.log('A'); resolve('A'); },(Math.random()+1)*1000) }) } function funcB(){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ console.log('B'); resolve('B'); },(Math.random()+1)*1000) }) } function funcC(){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ console.log('C'); resolve('C'); },(Math.random()+1)*1000) }) } Promise.all([funcA(),funcB(),funcC()]).then(()=>{console.log('上菜');}); ``` 要注意的是,在Promise.all()執行過程中只要有任一Promise物件執行發生錯誤或是Promise的reject情況,就會立即回傳一個reject狀態promise物件。 <br> ### Promise.race 只會回傳第一個 ```javascript function funcA(){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ console.log('A'); resolve('A'); },(Math.random()+1)*1000) }) } function funcB(){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ console.log('B'); resolve('B'); },(Math.random()+1)*1000) }) } function funcC(){ return new Promise(function(resolve,reject){ window.setTimeout(function(){ console.log('C'); resolve('C'); },(Math.random()+1)*1000) }) } Promise.race([funcA(),funcB(),funcC()]).then(()=>{console.log('上菜');}); ``` 相對於Promise.all()要等全部任務完成(resolve)才進行下一步,Promise.race()則是如同字面上含義的「競賽」一樣,只要有其中一個任務被resolve就會進行下一步。 <br><br><br>

    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