Skip to content

Instantly share code, notes, and snippets.

@Shimilbi
Last active January 17, 2024 13:43
Show Gist options
  • Save Shimilbi/e149baf08655cfc5739f243977a0a320 to your computer and use it in GitHub Desktop.
Save Shimilbi/e149baf08655cfc5739f243977a0a320 to your computer and use it in GitHub Desktop.
Custom promise to detect a click on discord button and return the button clicked (modified, modifications not tested). Follows TypeScript notations...
/**
*Parameters
promisedData must be declared in another part of the code prior to the call of this function.
dom_selector is only and example of use. this can perfectly be used backend for servers and output in a server-side file, another gui, a distant ftp, etc,
*Returns the promised data (here, wyth typescript, it is a string).
Is resolved when the given parameter promisedData is no longer undefined.
*Example of call:
let myPromiseOfData
// ...
myPromiseOfData = "MY HEART IS TRUE"
// ...
const myData = await getPromisedResults(myPromiseOfData)
*/
async function getPromisedResults(promisedData, dom_selector="") {
// Lands that now to later deduce the time elapsed before the resolution
const beforePromiseInMs = Date.now()
// Lands that now to later track the deadline
const delayInMs = 3000
// NOTE about previous line: this.configUponClick.ClickedButton and this.configUponExpiration.TimeClicksAreHandledInMs have been set by another function
const deadlineDate = beforePromiseInMs + delayInMs
// Prepares the future (will return the data, plus the time it took ot get it)
const promisedResults = new Promise(resolve => {
try {
const resolvePromise = () => {
const tickDate = Date.now()
console.log("\n checking out promise\n deadline: " + deadlineDate + "\n now: " + tickDate)
if (promisedData !== undefined) {
clearInterval(retryGetEvent)
const elapsedMs = Date.now() - beforePromiseInMs
resolve({
definedData: promisedData,
lapse: elapsedMs
})
if (dom_selector.length>0) document.querySelector(dom_selector).innerHTML += promisedData
console.log("\n getPromisedResults: Promise resolved: \nValue " + promisedData + " gotten after " + elapsedMs + "ms")
}
else if (tickDate >= deadlineDate) {
clearInterval(retryGetEvent)
resolve({
definedData: null,
lapse: delayInMs
})
if (dom_selector.length>0) document.querySelector(dom_selector).innerHTML += "Queue d'al."
}
}
let retryGetEvent = setInterval(resolvePromise, 1000) // Checks the event every second
} catch (err) { console.log(err) }
})
}
async function start() {
let myPromiseOfData
// ...
myPromiseOfData = "</br>MES INTENTIONS SONT PURES! 🦄"
// ...
const myData = await getPromisedResults(myPromiseOfData);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment