Simple Promises In Javascript

This is how to wrap a callback api in promises:

// Sample function with callback
function clientFactory() {
  return {
    request: (name, callback) => {
      callback(name)
    }
  }
}

let client = clientFactory()

client.request('a', console.log)

// Wrapping a callback into a promise

function returnCallbackResult(input) {
  let promise = new Promise(
    resolver => {
      let client = clientFactory()
      client.request(input, (a) => {
        resolver(a)
      })
  })
  return promise
}

returnCallbackResult('b').then( console.log )

// How to wrap a promise

function chainingPromise(input) {
  let promise = new Promise(
    resolver => {
      input.then( (a) => resolver(`wrapping ${a}`))
    }
  )
  return promise
}

chainingPromise( returnCallbackResult( 'c' ) ).then(console.log)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s