Last active
September 12, 2022 17:51
-
-
Save akirilyuk/29ce6f4343020580cfac66db38b403f3 to your computer and use it in GitHub Desktop.
Example, how to chain normal functions together with the await keyword in JS/TS to collect data first and execute the request later
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 functions = { | |
| data: {}, | |
| // we are using normal style function definitons for having a reference to this... | |
| select: function (select) { | |
| console.log('select', select) | |
| this.data.select = select | |
| return this | |
| }, | |
| eq: function (eq) { | |
| console.log('eq', eq) | |
| this.data.eq = eq | |
| return this | |
| }, | |
| limit: function (limit) { | |
| console.log('limit', limit) | |
| this.data.limit = limit | |
| return this | |
| }, | |
| filter: function (filter) { | |
| console.log('filter', filter) | |
| this.data.filter = filter | |
| return this | |
| }, | |
| then: async function (onfullfilled, onrejected) { | |
| console.log('awaiting via then!') | |
| // do some async stuff here | |
| try { | |
| console.log('doing a DB calll here') | |
| onfullfilled({ data: 'your data here' }) | |
| } catch (err) { | |
| console.error('got remote error', err.message) | |
| onrejected(err) | |
| } | |
| }, | |
| } | |
| const from = (name) => { | |
| const localFuncs = Object.assign({ data: { name } }, functions) | |
| console.log('returned local funcs', localFuncs) | |
| return localFuncs | |
| } | |
| async function main() { | |
| const stuff = await from('my dbName') | |
| .select('my column name') | |
| .eq('some data') | |
| .limit(1) | |
| console.log(stuff) | |
| } | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment