DEV Community

Zach
Zach

Posted on

.then()

This is going to be an embarrassingly basic post - basic in that it's about some basics: promises and callbacks.

You want to talk about tech debt? My list is a mile long, but somewhere near the bottom (like buried at the bottom) is the world of asynchronous functions and tools/topics like:

  • promises
  • async/await
  • callbacks
  • and more

Things move quickly at HR and it's difficult to set aside time for pure study or review. So my understanding of promises, for instance, hasn't progressed beyond the bare minimum. I mean the real minimum - can I throw some code near it to get what I want to happen.

I was debugging a problem with the Help Desk the other day. I was having a hard time redirecting my page after a form submission (the problem ended up being that I wasn't using preventDefault() in the event handler) and we were working on resolving that. Somewhere along that path, my interlocutor paused to point out an anti-pattern in some of the code we were investigating. The code was functional, but deficient.

I had been making http requests using helper functions like this:


const helper = (some_param, callback) => {

axios.post('http://url.com')
 .then(res => callback(null, res.data))
 .catch(err=> callback(err, null))

}
Enter fullscreen mode Exit fullscreen mode

Yikes.

Why had I been building functions like this? Well, for one, it worked. And that's really the whole list.

Back when I was first getting started with async, I had been making http requests using jQuery's .ajax tools and was getting comfortable using callbacks in that context.

Shortly after - I mean like the next day, if that - promises entered the mix. I never got to sit down with them for some semi-deep study before I joined a team that preferred .axios to .ajax. .axios returns prmoises, and being new to them, I asked a classmate how he'd handle the challenge I was facing converting an ajax call to axios. He suggested the model I demoed in code above. And it worked. So I'd been using it since.

I'm turning this into a long story.

Here's what the Help Desk helper had me do, and I've been using it pretty easily since:


const helper = (some_param) => {
  return axios.post('http://url.com')
}
Enter fullscreen mode Exit fullscreen mode

and then in the function that calls the helper:


reactEventHandler(param) => {
  helper(param)
   .this(res => setStatePerhaps(res.data)
   .catch(err=> callback(err, null))
}
Enter fullscreen mode Exit fullscreen mode

This is really surface-level stuff. But I'll call it a small win. And a win is a win.

Top comments (0)