Akkadu / styleguide

Developer styleguide for contributing to Akkadu repositories
https://akkadu.github.io/styleguide/
MIT License
0 stars 1 forks source link

[FEAT]: Prefer Async/Await #7

Open HoukasaurusRex opened 4 years ago

HoukasaurusRex commented 4 years ago

do

const request = async(params) => {
  const options = filterParams()
  const res = await fetch(options)
  const someInfo = await res.getSomeInfo()
  const json = await res.json()
  const data = mapMyData()
  return { ...data, ...someInfo }
}

don't

const request = (params) => new Promise((resolve, reject) => {
  const options = filterParams()
  let response
  let data = {}
  return fetch(options)
    .then(res => 
      response = res
      return res.getSomeInfo()
    )
    .then(someInfo =>
      data.someInfo = someInfo
      return response
    )
    .then(res => res.json())
    .then(json => { ...data, ...json })
})
TNieminen commented 4 years ago

This is a good proposal. A special case I'd like to point out is for dynamic module imports.

do

const Streamer =(await import('@akkadu/rtc-streamer-consumer')).default
const streamer = new Streamer(streamerConfig)
// some other functions that need to await for streamer to be intialized

don't

this.streamer = await import('@akkadu/rtc-streamer-consumer')
        .then(({ default: Streamer }) => new Streamer(this.streamerConfig))
this.initializeStreamerListeners()
this.subscribeToChannels()

// nor

let streamer
import('@akkadu/rtc-streamer-consumer')
      .then(({ default: Streamer }) => {
        const streamer = new Streamer(streamerConfig)
        return streamer 
      })
      .then((streamer) => {
        // other functions that need to wait for streamer to initialize
      })