1.0.2 • Published 8 years ago

when-scopes v1.0.2

Weekly downloads
2
License
ISC
Repository
-
Last release
8 years ago

A common pattern in syncronous code is to return functions early:

function getUserInfo() {

    var user = getCurrentUser();
    if (!user) {
         return { error: 'No current user, please log in' };
    }

    if (!hasConnection()) {
        return { error: 'No connection' };
    }

    return user.api.getInfo();

}

If getCurrentUser(), hasConnection() and user.api.getInfo() where async, this pattern would be hard to implement without using rejected promises for program flow. when-scopes makes this possible.

function getUserInfo() {
    return whenScopes(finish => {

        return getCurrentUser()
            .then(user => {
                if (!user) {
                    return finish({ error: 'No current user, please log in' });
                }

                return hasConnection();
            })
            .then(connected => {
                if (!connected) {
                    return finish({ error: 'No connection' });
                }
                return user.api.getInfo();
            });

    })
});
   

TODO

  • Write real tests
  • Add the test case for catching errors
  • Write a proper readme