Pattern for functions that get promises, and then create and return new promises

There's nothing deep or official about this. But I'm new to promises and it took me a while to work out how things wanted to nest when I used a function that returns a promise, and then wanted to return a promise of my own.



function myFunction(myArgs) {
    return new Promise(function(resolve, reject) {
        callThingThatReturnsPromise(myArgs)
        .then(function(gotThing) {
            //compute with gotThing
            resolve(computedFromGotThing);
        ).catch(err) {
            //do stuff with error
            reject(computedFromError);
        );
    );
}

The point here is that we want to write the.then(...) and .catch(...) handlers for the promise we get in a context where we can see the resolve and reject functions for the promise we are creating.

And, just to review...

When using a promise, we write handler functions to pass to then and catch.

When creating a promise, we are* given resolve and reject functions to call.

* Technically we will be given resolve and reject functions, when the function we give to the Promise constructor is called.

(I think promises are a quick and painless way to write asynchronous code... after we finish long and painful task of understanding them.)

Comments

  1. Thanks for writing this explanation. This looks very similar to the way I have used call backs in the past especially with Ajax functions. With callbacks, I would pass in a success and failure callback that would be called when the data returned, here it looks like it acts the same except you are constructing the then with the returned data and then executing code or another function. is that correct? Do you have to call resolve() and reject(), or could you just have code in the then function?

    ReplyDelete

Post a Comment

Popular posts from this blog

Callback, Promise, Observable, and Doughnuts

Learn grid and grid-template-areas FIRST!!!

The Day TDD Started Working for Me