Promise簡單學習 ,備忘react
Promise用同步的寫法解決了異步回調金字塔的問題編程
如promise
getData1(data1 => { getData2(data1, data2 => { getData3(data2, data3 => { getData4(data3, data4 => { getData5(data4, data5 => { // 終於取到data5了 }) }) }) }) })
用Promise異步
getData1() .then(getData2) .then(getData3) .then(getData4) .then(getData5) .then(data => { // 取到最終data了 })
基礎用法函數
let p = new Promise((resolve, reject) => { // 作一些事情 // 而後在某些條件下resolve,或者reject if (/* 條件隨便寫^_^ */) { resolve() } else { reject() } }) p.then(() => { // 若是p的狀態被resolve了,就進入這裏 }, () => { // 若是p的狀態被reject })
模擬紅綠燈學習
componentDidMount(){ function red(){ console.log("red"); } function yellow(){ console.log("yellow"); } function green(){ console.log("green"); } let light = (fn,timer) => new Promise(resolve=>{ setTimeout(function(){ fn(); resolve(); },timer) }) function start(){ Promise.resolve().then(()=>{ light(red,3000) }).then(()=>{ light(yellow,5000) }).then(()=>{ light(green,8000) }) } start(); }
我寫在react項目裏test spa
記錄下來備忘。code