I have seen a lot of code that looks like this:

let record = getRecordFromCache(id);  
if (record) {  
  // do something
} else {
  fetchRecord(id).then(record => {
    // do something
  });
}

For the sake of simplicity lets just assume the function called fetchRecord makes an ajax request, caches the results and returns a promise, and getRecordFromCache returns a cached record or undefined.

Even if the // do something is as simple as a single function call, I still feel like this piece of code is a candidate for some drying up. Especially if this snippet is being used in multiple places.

I want to dry this into a single method called getRecord. So how do you dry up a piece of code that is half of the time synchronous and the other half asynchronous?

That is where Promise.resolve really shines. Promise.resolve allows you to take a piece of data and wrap in an immediately resolving promise. This allows us to write a function like so:

function getRecord(id) {  
  let record = getRecordFromCache(id);
  if (record) {
    return Promise.resolve(record);
  } else {
    return fetchRecord(id);
  }
}

Since this function is always returning a promise, one that is immediately resolving the record or one that resolves the record after an ajax request. That allows us to rewrite our original code to make it much cleaner:

getRecord(id).then(record => {  
  // do something
});

In the above code, if our record is cached, then it will immediately resolve that record from the cache, otherwise it will fetch the record and then resolve with it. Neat.

© 2017. All Rights Reserved.

Proudly published with Ghost