constgetPuzzle=callback=>{constrequest=newXMLHttpRequest()request.addEventListener('readystatechange',e=>{if(e.target.readyState===4&&e.target.status===200){constdata=JSON.parse(e.target.responseText)callback(undefined,data.puzzle)}elseif(e.target.readyState===4){callback('An error has taken place',undefined)}})request.open('GET','http://puzzle.mead.io/puzzle?wordCount=3')request.send()}// callback functiongetPuzzle((error,puzzle)=>{if(error){console.log(`Error:${error}`)}else{console.log(puzzle)}})
// CallbackconstgetDataCallBack=callback=>{setTimeout(()=>{callback(undefined,'This is the callback data')},2000)}getDataCallBack((err,data)=>{if(err){}else{console.log(data)}})// PromiseconstmyPromise=newPromise((resolve,reject)=>{setTimeout(()=>{// 成功做什麼事resolve('This is the promise resolve')// 失敗做什麼事reject('This is the promise reject')},2000)})myPromise.then(data=>{console.log(data)},err=>{console.log(err)})
constgetDataPromise=num=>newPromise((resolve,reject)=>{setTimeout(()=>{typeofnum==='number'?resolve(num*2):reject('Number must be provided')},2000)})getDataPromise(10).then(data=>{getDataPromise(data).then(data=>{console.log(data)// 40}).catch(err=>{console.log(err)})}).catch(err=>{console.log(err)})// better waygetDataPromise(10).then(data=>{returngetDataPromise(data)}).then(data=>{console.log(data)// 40}).catch(err=>{console.log(err)})
也有一些非同步模式的變體可以使用
Promise.all: 等所有都完成再進行下一步
Promise.race: 只要一個先完成就進行下一步
fetch
fetch 會回傳 promise object,因此也可以用 then 去接
12345678910111213141516
constfetch=require('node-fetch')fetch('http://puzzle.mead.io/puzzle',{}).then(response=>{if(response.status===200){returnresponse.json()}else{thrownewError('Unable to fetch the puzzle')}}).then(data=>{console.log(data.puzzle)}).catch(error=>{console.log(error)})
constprocessData=async()=>{// throw new Error('error')return'hi'}processData().then(data=>{console.log(data)}).catch(error=>{console.log(error)})
12345678910111213141516171819
// node need to requireconstfetch=require('node-fetch')constgetPuzzle=asyncwordCount=>{constresponse=awaitfetch(`http://puzzle.mead.io/puzzle?wordCount=${wordCount}`)if(response.status===200){constdata=awaitresponse.json()returndata.puzzle}else{thrownewError('Unable to get puzzle')}}getPuzzle('2').then(puzzle=>{console.log(puzzle)}).catch(err=>{console.log(`Error:${err}`)})