JavaScript async/await Class Promise Examples
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
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!' );
});
JavaScript
INFO