Last active
July 26, 2022 14:14
-
-
Save SparK-Cruz/381012bbb675aeb31114f70490f48092 to your computer and use it in GitHub Desktop.
Deferrence in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
module.exports = function scope(block) { | |
const deferred = []; | |
const defer = function(callback, args) { | |
deferred.unshift({target: this, callback, args}); | |
} | |
try { | |
return block(defer); | |
} finally { | |
deferred.forEach(o => o.callback.apply(o.target, o.args)); | |
} | |
} | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const scope = require('./scope.js'); | |
const fakeDb = { | |
openned: false, | |
open: function() { console.log('openned'); this.openned = true; }, | |
close: function() { console.log('closed'); this.openned = false; }, | |
}; | |
const fakeModel = { | |
save: (db) => db.openned ? 'working with DB' : 'failed!', | |
} | |
const fakeSocket = { | |
connect: () => console.log('connected'), | |
disconnect: () => console.log('disconnected'), | |
} | |
scope(function(defer){ | |
fakeDb.open(); | |
defer(fakeDb.close, []); | |
fakeSocket.connect(); | |
defer(fakeSocket.disconnect, []); | |
console.log('do something with DB and Socket'); | |
console.log(fakeModel.save(fakeDb)); | |
}); | |
// openned | |
// connected | |
// do something with DB and Socket | |
// working with DB | |
// disconnected | |
// closed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is made for "synchronous-like" code, ideal to use with async/await but not with callbacks.