Skip to content

Instantly share code, notes, and snippets.

@srph
Last active May 3, 2017 08:23
Show Gist options
  • Select an option

  • Save srph/6ecf133a961c3dd9a4d1250d34af601f to your computer and use it in GitHub Desktop.

Select an option

Save srph/6ecf133a961c3dd9a4d1250d34af601f to your computer and use it in GitHub Desktop.
JS: Exclude null values from resolved value

why

This comes in handy when a callback function returns 2 things: undefined or Promise. This happens when:

  • Callback may return undefined when confirmation dialog (window.confirm) is cancelled.
  • Otherwise, just proceeds, and finally callback returns a Promise which does the ajax request
function callback(id) {
  if (!confirm('Are you sure to delete?')) {
    return;
  }
  
  return axios.delete(`/products/${id}`);
}

before

Promise.resolve(promise)
  .then(res => {
    return !res
  })
  .then(res => {
    // Do something
  });

after

resolve(promise)
  .then(res => {
    // Do something
  });

footguns

Careful, if you don't return something inside a then, you're going to waste a lot of time why your program's acting weird.

// bad
function callback(id) {
  if (!confirm('Are you sure to delete?')) {
    return;
  }
  
  return axios.delete(`/products/${id}`)
    .then(res => {
      // do something
      // not return
    });
}

// good
function callback(id) {
  if (!confirm('Are you sure to delete?')) {
    return;
  }
  
  return axios.delete(`/products/${id}`)
    .then(res => {
      // do something
      return res;
    });
}
function resolve(promise) {
return Promise.resolve(promise)
.then(res => {
return res
? res
: Promise.reject();
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment