Skip to content

Instantly share code, notes, and snippets.

@BrianLitwin
Last active March 19, 2019 17:41
Show Gist options
  • Save BrianLitwin/f2ff723db1cf13cc9ce981759cf6b7a8 to your computer and use it in GitHub Desktop.
Save BrianLitwin/f2ff723db1cf13cc9ce981759cf6b7a8 to your computer and use it in GitHub Desktop.

A promise is an object representing the eventual completion or failure of an asynchronous operation Essentially, a promise is a returned object onto which you attach callbacks, instead of passing callbacks into a function

How to write createAudioFileAsync(audioSettings, successCallback, failureCallback) using Promises? createAudioFileAsync(audioSettings).then(successCallback, failureCallback) or

const promise = createAudioFileAsync(audioSettings); 
promise.then(successCallback, failureCallback);

A promise comes with guarantees:

  • Callbacks will never be called before the completion of the current run of the JavaScript event loop.
  • Callbacks added with then() even after the success or failure of the asynchronous operation, will be called, as above.
  • Multiple callbacks may be added by calling then() several times. Each callback is executed one after another, in the order in which they were inserted.
Chaining

When chaining, the then() function returns a new Promise, different from the original.

async function doSomething(r) {
  console.log(r)
  if (r > 4) {
    throw new Error("found error")
  }
  return r + 1
}
async function start() {

await doSomething(1).then(function(result){
  return doSomething(result)
}).then(function(result){
  doSomething(result)
})

doSomething(1)
.then(r => doSomething(r))
.then(r => doSomething(5)).catch((er) => console.log(er))

}

start()
function rimraf(callback) {
  throw new Error("new")
  return 0
}

function removeDir() {
  return new Promise((res, rej) => {
    rimraf((error) => {
      if (error) {
        rej(error)
      } else {
        res(0)
      }
    })
  })
}

const makeClear = (
  async function clear() {
    await removeDir().catch((err) => {
      console.log(err)
    })
  }
)

makeClear()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment