Quick actions

cmd+k|ctrl+k

Navigation

Languages

JavaScript async/await Class Promise Examples

Snippet info

Language

JavaScript

Visibility

public

Author

myles

Created

2018-01-15T02:31:04Z

Updated

2018-01-15T02:38:50Z

let WiFiLib = {

	addNetwork: function( netID ){

		return new Promise( function( resolve, reject ){

			if( netID > -1 ){
				resolve( true );
			} else {
				reject( 'Invalid network ID!' );
			}

		});

	},

	connect: function( netID ){

		return new Promise( function( resolve, reject ){

			resolve( true );
			//reject( 'Unable to connect to wifi!' );

		});

	}

};

class WiFi {

	constructor(){
		this.delay = 2000;
		this.netID = -1;
	}

	async connect(){

		try {

			let netID = this.add();
			this.netID = await netID;

			await this.doConnect();

			return true;

		} catch( error ){

			console.log( 'Wifi connect catch error: ', error );
            await this.timeout();
            console.log( 'Wifi connect catch error after timeout' );
			throw error;
		}
	}

	async add(){

		const networkAdded = await WiFiLib.addNetwork( 2 );
		await this.timeout();

		return networkAdded;
	}

	async doConnect(){

		const networkConnected = await WiFiLib.connect( this.netID );
		await this.timeout();

		return networkConnected;
	}

	/**
	 * Synchronous Sleep/Timeout `await this.timeout()`
	 */
	timeout( customDelay ) {
		let delay = customDelay ? parseInt( customDelay ) : parseInt( this.delay );
		return new Promise(function(resolve, reject) {
			setTimeout(resolve, delay);
		});
	}
}

class Provisioner {

	constructor( wifi ){
		this.wifi = wifi;
	}

	async startProvision(){

		try {

			await this.wifi.connect();
			//do some provision stuff
			
			return true;

		} catch ( error ){

			console.log( 'Provisioner Catch', error );
			
			let doRetry = this.doRetry( false );
			await doRetry;
			
			if( doRetry ){
				this.startProvision();
			} else {
				throw error;
			}
			
		}

	}
	
	async doRetry( shouldDo ){
			await this.timeout();
			return shouldDo;
	}
	
		/**
	 * Synchronous Sleep/Timeout `await this.timeout()`
	 */
	timeout( customDelay ) {
		let delay = customDelay ? parseInt( customDelay ) : parseInt( this.delay );
		return new Promise(function(resolve, reject) {
			setTimeout(resolve, delay);
		});
	}
}

let wifiConnector = new WiFi();
let provisioning = new Provisioner( wifiConnector );

provisioning.startProvision().then( ()=>{
	console.log( 'Provisioner Complete!' );
}, error => {
	console.log( 'Provisioner Error!' );
});
INFO