Promises
Added in ES6
Promises are similar to event listeners with a few important differences.
Lets you separate the parameters from the function code.
link - promisesjs.org
A promise can only suceed or fail once
Needed to add a Promises reference a few years ago ??
Nested Callbacks
Add the 'then'
function asyncMethod(message) {
return new Promise( function (succeed, fail) {
setTimeOut( function() {
console.log(message);
succeed();
}, 400)
});
}
asyncMethod('Connect to Database').then( function() {
asyncMethod('Verify User Details').then( function() {
asyncMethod('Check Permissions').then( function() {
asyncMethod('Update User').then( function() {} )
})
})
})
Step 2 - Remove the anonymous functions
function asyncMethod(message) {
return new Promise( function (succeed, fail) {
setTimeOut( function() {
console.log(message);
succeed();
}, 400)
});
}
function fn_verifyUserDetails() {
asyncMethod('Verify User Details')
.then( fn_checkPermissions )
}
function fn_checkPermissions() {
asyncMethod('Check Permissions')
.then( fn_updateUser )
}
function fn_updateUser() {
asyncMethod('Update User')
.then( function () {} )
}
asyncMethod('Connect to Database')
.then( fn_verifyUserDetails )
Step 3 - Chain together
function asyncMethod(message) {
return new Promise( function (succeed, fail) {
setTimeOut( function() {
console.log(message);
suceed();
}, 400)
});
}
function fn_verifyUserDetails() {
return asyncMethod('Verify User Details')
}
function fn_checkPermissions() {
return asyncMethod('Check Permissions')
}
function fn_updateUser() {
return asyncMethod('Update User')
}
asyncMethod('Connect to Database')
.then( fn_verifyUserDetails )
.then( fn_checkPermissons )
.then( fn_updateUser )
.then( function () {} )
© 2021 Better Solutions Limited. All Rights Reserved. © 2021 Better Solutions Limited TopPrevNext