Home Chain Javascript function before promise function to only call based on initial function
Reply: 3

Chain Javascript function before promise function to only call based on initial function

sMyles
1#
sMyles Published in 2018-01-12 18:54:59Z

Consider the following code that works correctly (functions below are normally inside API object):

let Query = async function( method, endpoint, options, successCode, obKey ){

    return true;
    //return new Error( 'Could not complete query!' );
    
};

let isAlive = async function( options ){
	try {
		return await Query( 'GET', '/heart', options, 204 );
	} catch( error ){
		return error;
	}
};

let getNetworks = async function(options) {
	try {
		return await Query( 'GET', '/networks', options, 200, 'networks' );
	} catch( error ){
		return error;
	}
};

// Standard promise method works
isAlive().then( () => {
		getNetworks().then( result => {
			console.log( 'GET NETWORKS', result );
		}).catch( error => {
			console.log( 'GET NETWORKS ERROR', error.message );
		});
	}
);

// BUT to make for cleaner code base, how can I only call next function in chain
// based on isAlive() function?

How can I handle the isAlive() function to allow for chaining, but only to execute the Promise based functions that are called after isAlive() based on result in isAlive(), like below?

isAlive().getNetworks().then( result => {
    console.log( 'GET HOMIE NETWORKS', result );
}).catch( error => {
    console.log( 'GET HOMIE NETWORKS ERROR', error.message );
});

Yes I understand it could be done this way from inside an async function, however, there will be times where await isAlive(); would not be possible ... and was hoping to be able to create an easy helper function that can be chained onto ... is this possible at all? Without having to use .then( ()=> { ... } )?

Glot.IO: https://glot.io/snippets/exas8rbxyu JSFiddle: https://jsfiddle.net/tripflex/sj78297k/

I was able to figure out some basic chaining by returning this, but not sure how to implement something like this with Promises.

var myObj = {
	hasPerms: false,
	check : function( doChain ){
	    this.hasPerms = doChain;
		console.log( 'Checkinnngggg...' );
		return this;
	},
	then : function( callback ){
	    if( this.hasPerms ){
	        callback();
	    } else {
	        return false;
	    }
	}
};

//"chain, chain, chain..."
myObj.check( false ).then( function(){
    console.log( 'I GOT FOO\'D');
});

trincot
2#
trincot Reply to 2018-01-12 19:00:41Z

In your example you can just pass the function reference to the then method:

isAlive().then(getNetworks).then( result => {
    console.log( 'GET NETWORKS', result );
}).catch( error => {
    console.log( 'GET NETWORKS ERROR', error.message );
});

It is indeed a good practice to try to avoid nested promises, but instead return each promise to the outer promise chain.

guest271314
3#
guest271314 Reply to 2018-01-12 19:04:34Z

You can define a method on the Promise prototype, though you would need to use .then() within the method

Promise.prototype.getNetworks = function(value) {
  // do stuff
  return this.then(function(data) {
    // do stuff
    return data
  })
  .catch(function(err) {
    throw err
  })
};

you could then use the pattern

isAlive().getNetworks();
JBone
4#
JBone Reply to 2018-01-13 14:05:09Z

see if this can help

async function myFunc() {
throw new Error("Whoops!");
}

and here in the call, you can catch the error (reject)

myFunc()
.catch(function(rej, resolve)
   {console.log(`in the catch block rej ${rej}`
)});
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.325419 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO