I have the following function that I wish to turn into a promise:
const blockRequest = (context) => {
let blockRequest = false;
let limitLocation;
const generalLocation = "/limits/general/limits";
let generalTime;
let generalNum;
let limitTime;
let limitNum;
const newTime = new Date().getTime();
if (context.auth != undefined) {
limitLocation = "/users/"+context.auth.uid+"/limits";
} else {
limitLocation = "/limits/"+context.rawRequest.ip+"/limits";
}
admin.database().ref(generalLocation+"/generalNum")
.set(admin.database.ServerValue.increment(1))
.then(()=>{
return admin.database().ref(generalLocation).once("value");
})
.then((snapshot)=>{
if (snapshot.val() == undefined) {
generalNum = 0;
generalTime = newTime;
} else {
generalTime = snapshot.val().generalTime;
generalNum = snapshot.val().generalNum;
}
if ( newTime - generalTime>3000) {
generalNum = 1;
} else if (newTime - generalTime <=300 &&
generalNum < 300) {
} else {
console.log("General Request Blocked");
blockRequest = true;
}
return admin.database().ref(generalLocation)
.set({generalTime: newTime, generalNum: generalNum});
})
.then(()=>{
if (blockRequest) {
return blockRequest;
} else {
return admin.database().ref(limitLocation+"/limitNum")
.set(admin.database.ServerValue.increment(1));
}
})
.then(()=>{
return admin.database().ref(limitLocation).once("value");
})
.then((snapshot)=>{
if (snapshot.val().limitTime == undefined) {
limitNum = snapshot.val().limitNum;
limitTime = newTime;
} else {
limitTime = snapshot.val().limitTime;
limitNum = snapshot.val().limitNum;
}
if ( newTime - limitTime>10000) {
limitNum = 1;
} else if (newTime - limitTime <=10000 &&
limitNum < 20) {
} else {
console.log("Specific Request Blocked");
blockRequest = true;
}
return admin.database().ref(limitLocation)
.set({limitTime: newTime, limitNum: limitNum});
})
.then(()=>{
console.log(blockRequest)
return blockRequest;
})
.catch((error)=>{
console.log(error.message);
return true;
});
};
I also have a function that I would like to call that looks like:
exports.limiterTest = functions.https.onCall(async(data, context)=>{
const result = await blockRequest(context)
console.log("hello")
});
I would like blockRequest to finish running before anything else in limiterTest runs. I think in order for this to function as I intend, I need blockRequest to return a promise. However, I am not sure how to construct this, especially with the chaining .then and .catch statements.
Thanks for your time!
Related
I wanted to make a FPS Unlimiter Userscript for gpop.io because the current fps cap is 60 and wanted to increase to 240fps and I don't understand JavaScript well enough to know what I am doing and am requesting help, The Section Of pageScript.js, I have The pageScript.js in the URL and The Code Below
!function pageScript() {
let speedConfig = {
speed: 1.0,
cbSetIntervalChecked: true,
cbSetTimeoutChecked: true,
cbPerformanceNowChecked: true,
cbDateNowChecked: true,
cbRequestAnimationFrameChecked: false,
};
const emptyFunction = () => {};
const originalClearInterval = window.clearInterval;
const originalclearTimeout = window.clearTimeout;
const originalSetInterval = window.setInterval;
const originalSetTimeout = window.setTimeout;
const originalPerformanceNow = window.performance.now.bind(
window.performance
);
const originalDateNow = Date.now;
const originalRequestAnimationFrame = window.requestAnimationFrame;
let timers = [];
const reloadTimers = () => {
console.log(timers);
const newtimers = [];
timers.forEach((timer) => {
originalClearInterval(timer.id);
if (timer.customTimerId) {
originalClearInterval(timer.customTimerId);
}
if (!timer.finished) {
const newTimerId = originalSetInterval(
timer.handler,
speedConfig.cbSetIntervalChecked
? timer.timeout / speedConfig.speed
: timer.timeout,
...timer.args
);
timer.customTimerId = newTimerId;
newtimers.push(timer);
}
});
timers = newtimers;
};
window.addEventListener("message", (e) => {
if (e.data.command === "setSpeedConfig") {
speedConfig = e.data.config;
reloadTimers();
}
});
window.postMessage({ command: "getSpeedConfig" });
window.clearInterval = (id) => {
originalClearInterval(id);
timers.forEach((timer) => {
if (timer.id == id) {
timer.finished = true;
if (timer.customTimerId) {
originalClearInterval(timer.customTimerId);
}
}
});
};
window.clearTimeout = (id) => {
originalclearTimeout(id);
timers.forEach((timer) => {
if (timer.id == id) {
timer.finished = true;
if (timer.customTimerId) {
originalclearTimeout(timer.customTimerId);
}
}
});
};
window.setInterval = (handler, timeout, ...args) => {
console.log("timeout ", timeout);
if (!timeout) timeout = 0;
const id = originalSetInterval(
handler,
speedConfig.cbSetIntervalChecked ? timeout / speedConfig.speed : timeout,
...args
);
timers.push({
id: id,
handler: handler,
timeout: timeout,
args: args,
finished: false,
customTimerId: null,
});
return id;
};
window.setTimeout = (handler, timeout, ...args) => {
if (!timeout) timeout = 0;
return originalSetTimeout(
handler,
speedConfig.cbSetTimeoutChecked ? timeout / speedConfig.speed : timeout,
...args
);
};
// performance.now
(function () {
let performanceNowValue = null;
let previusPerformanceNowValue = null;
window.performance.now = () => {
const originalValue = originalPerformanceNow();
if (performanceNowValue) {
performanceNowValue +=
(originalValue - previusPerformanceNowValue) *
(speedConfig.cbPerformanceNowChecked ? speedConfig.speed : 1);
} else {
performanceNowValue = originalValue;
}
previusPerformanceNowValue = originalValue;
return Math.floor(performanceNowValue);
};
})();
// Date.now
(function () {
let dateNowValue = null;
let previusDateNowValue = null;
Date.now = () => {
const originalValue = originalDateNow();
if (dateNowValue) {
dateNowValue +=
(originalValue - previusDateNowValue) *
(speedConfig.cbDateNowChecked ? speedConfig.speed : 1);
} else {
dateNowValue = originalValue;
}
previusDateNowValue = originalValue;
return Math.floor(dateNowValue);
};
})();
// requestAnimationFrame
(function () {
let dateNowValue = null;
let previusDateNowValue = null;
const callbackFunctions = [];
const callbackTick = [];
const newRequestAnimationFrame = (callback) => {
return originalRequestAnimationFrame((timestamp) => {
const originalValue = originalDateNow();
if (dateNowValue) {
dateNowValue +=
(originalValue - previusDateNowValue) *
(speedConfig.cbRequestAnimationFrameChecked
? speedConfig.speed
: 1);
} else {
dateNowValue = originalValue;
}
previusDateNowValue = originalValue;
const dateNowValue_MathFloor = Math.floor(dateNowValue);
const index = callbackFunctions.indexOf(callback);
let tickFrame = null;
if (index == -1) {
callbackFunctions.push(callback);
callbackTick.push(0);
callback(dateNowValue_MathFloor);
} else if (speedConfig.cbRequestAnimationFrameChecked) {
tickFrame = callbackTick[index];
tickFrame += speedConfig.speed;
if (tickFrame >= 1) {
while (tickFrame >= 1) {
callback(dateNowValue_MathFloor);
window.requestAnimationFrame = emptyFunction;
tickFrame -= 1;
}
window.requestAnimationFrame = newRequestAnimationFrame;
} else {
window.requestAnimationFrame(callback);
}
callbackTick[index] = tickFrame;
} else {
callback(dateNowValue_MathFloor);
}
});
};
window.requestAnimationFrame = newRequestAnimationFrame;
})();
}()
//# sourceURL=pageScript.js
I was trying to read through the code to find what was capping the fps but I wasn't able to find anything that was easy enough for me to understand.
goBack() {
this.generateCode()
this.offerService.removeAllSelectedProducts(this.offer.products)
.pipe(filter((removedProducts) => removedProducts))
.subscribe(() => this.router.navigate(["/home"]))
}
generateCode() {
let offerCode
if (navigator.onLine) {
this.customerId = localStorage.getItem(LocalstorageKeyEnum.SELECTED_CUSTOMER)
? JSON.parse(localStorage.getItem(LocalstorageKeyEnum.SELECTED_CUSTOMER)).id
: "NEW";
if (this.customerId === "NEW") {
this.countNewOffers = 1;
}
else {
this.loading = true;
let offersByIdObservable = this.offerService.getOpportunityCount(this.customerId)
offersByIdObservable.pipe(untilDestroyed(this))
.subscribe(
(data) => {
this.loading = false;
this.countNewOffers = data + 1;
},
(error) => {
if (error.status === 404) {
this.loading = false;
this.countNewOffers = 1;
}
}
);
}
offerCode = "OF-" + this.customerId + "-" + (this.countNewOffers ? this.countNewOffers : "NEW");
this.offer.code = offerCode;
localStorage.setItem(LocalstorageKeyEnum.OFFER, JSON.stringify(this.offer));
} else {
this.loading = false;
}
}
}
I have this two functions, when I click on a button I call the function goBack() that launches the generateCode()
This function (generateCode()) makes the request (the status code is 200). I have tried to debug and it doesn't enter subscribe data or error, so this.countNewOffers results undefined.
I don't understand why it doesn't enter in data or error, but the api call is a 200 with blank response. (but if I call from another place, like swagger, it works and give me back a number)
I'm making the 2048 game, but the window.addEventListener("keydown", handleInput, {once:true}); does not firing. But if I console.log(e.key), I get the message that I pressed the button (ArrowUp, -Down and os on), but the tile does not move. Can anyone help please?
This is the index.js file that contains the eventlistener.
import Grid from "./grid.js";
import Tile from "./tile.js";
const gameBoard = document.getElementById('game-board');
const grid = new Grid(gameBoard);
grid.randomEmptyCell().tile = new Tile(gameBoard);
grid.randomEmptyCell().tile = new Tile(gameBoard);
setupInput();
function setupInput() {
window.addEventListener("keydown", handleInput, { once: true });
}
async function handleInput(e) {
console.log(e.key);
switch (e.key) {
case "ArrowUp":
if(!canMoveUp()) {
setupInput();
return;
}
await moveUp()
break
case "ArrowDown":
if(!canMoveDown()) {
setupInput();
return;
}
await moveDown()
break
case "ArrowLeft":
if(!canMoveLeft()) {
setupInput();
return;
}
await moveLeft()
break
case "ArrowRight":
if(!canMoveRight()) {
setupInput();
return;
}
await moveRight()
break
default:
setupInput()
return
}
grid.cells.forEach(cell => cell.merTiles());
const newTile = new Tile(gameBoard);
grid.randomEmptyCell().tile = newTile;
if (!canMoveUp() && !canMoveDown() && !canMoveLeft() && !canMoveRight()) {
newTile.waitForTransition(true).then(() => {
alert("You lose!");
});
} return
setupInput();
}
function moveUp() {
return slideTiles(grid.cellsByColumn);
}
function moveDown() {
return slideTiles(grid.cellsByColumn.map(column => [...column].reverse()));
}
function moveLeft() {
return slideTiles(grid.cellsByRow);
}
function moveRight() {
return slideTiles(grid.cellsByRow.map(row => [...row].reverse()));
}
function slideTiles(cells) {
return Promise.all(
cells.flatMap(group => {
const promises = [];
for (let i = 1; i < group.length; i++) {
const cell = group[i];
if (cell.tile == null) continue;
let lastValidCell;
for (let j = i - 1; j >= 0; j--) {
const moveToCell = group[j];
if (!moveToCell.canAccept(cell.tile)) break;
lastValidCell = moveToCell;
}
if (lastValidCell != null) {
promises.push(cell.tile.waitForTransition());
if (lastValidCell.tile != null) {
lastValidCell.mergeTile = cell.tile;
} else {
lastValidCell.tile = cell.tile;
}
cell.tile = null;
}
}
return promises;
}));
}
function canMoveUp() {
return canMove(grid.cellsByColumn);
}
function canMoveDown() {
return canMove(grid.cellsByColumn.map(column => [...column].reverse()));
}
function canMoveLeft() {
return canMove(grid.cellsByRow);
}
function canMoveRight() {
return canMove(grid.cellsByRow.map(row => [...row].reverse()));
}
function canMove(cells) {
return cells.some(group => {
return group.some((cell, index) => {
if (index === 0) return false;
if (cell.tile == null) return false;
const moveToCell = group[index - 1];
return moveToCell.canAccept(cell.tile);
});
});
}
See mdn page:
EventTarget.addEventListener()
A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked. If not specified, defaults to false.
if you remove {once: true}, it will can work more than once.
Also one more thing, you use console.log(e.key) but you use e.keyCode in switch cases. On MDN, keyCodes are actually codes.Code values for keyboard events
so, you should either change your switch case conditions to e.key to use the same values: Key values for keyboard events
or change the case values from text to keyCode
lets say i have a function that gets a random number, then returns wether that number meets a condition and if not it throws an error:
const randFunc = () => {
let a = Math.floor(Math.random() * 10)
if(a === 5){
return a
} else {
throw new Error('Wrong Num')
}
}
what i would like to know is if i can loop through this function until i get '5'
try {
randFunc()
} catch {
//if error is caught it re-trys
}
Thanks!
Just an standard endless loop:
const randFunc = () => {
let a = Math.floor(Math.random() * 10);
if(a === 5){
return a;
} else {
throw new Error('Wrong Num');
}
}
function untilSuccess() {
while (true) {
try {
return randFunc();
} catch {}
}
}
console.log(untilSuccess());
Or a recursive option:
const randFunc = () => {
let a = Math.floor(Math.random() * 10);
if (a === 5) {
return a;
} else {
throw new Error('Wrong Num');
}
}
function untilSuccess() {
try {
return randFunc();
} catch {
return untilSuccess();
}
}
console.log(untilSuccess());
This one can blow your stack, depending on your retries (not so much of a problem for this though).
Something like this might work for you
let success = false;
while (!success) {
try {
randFunc();
success = true;
} catch { }
}
This code will cause an endless loop if randFunc() keeps throwing.
You can set up a recursive function to keep trying something until it works:
const randFunc = () => {
let a = Math.floor(Math.random() * 10)
if(a === 5){
return a
} else {
throw new Error('Wrong Num')
}
}
getfive()
//getfive is recursive and will call itself until it gets a success
function getfive(){
try{
randFunc()
console.log('GOT 5!')
}
catch(err){
console.log('DID NOT GET 5')
getfive()
}
}
The bot replies well when a command is sent.
How do I make the WhatsApp web bot to reply with an image pulled from a URL? I want it to be able to reply with an image pulled from a URL, for example, www.school.com/pic.jpg. On the code if a user text #time it replies with time and Date but I want it to reply with an image.
//
// FUNCTIONS
//
// Get random value between a range
function rand(high, low = 0) {
return Math.floor(Math.random() * (high - low + 1) + low);
}
function getElement(id, parent){
if (!elementConfig[id]){
return false;
}
var elem = !parent ? document.body : parent;
var elementArr = elementConfig[id];
for (var x in elementArr){
var pos = elementArr[x];
if (isNaN(pos*1)){ //dont know why, but for some reason after the last position it loops once again and "pos" is loaded with a function WTF. I got tired finding why and did this
continue;
}
if (!elem.childNodes[pos]){
return false;
}
elem = elem.childNodes[pos];
}
return elem;
}
function getLastMsg(){
var messages = document.querySelectorAll('.msg');
var pos = messages.length-1;
while (messages[pos] && (messages[pos].classList.contains('msg-system') || messages[pos].querySelector('.message-out'))){
pos--;
if (pos <= -1){
return false;
}
}
if (messages[pos] && messages[pos].querySelector('.selectable-text')){
return messages[pos].querySelector('.selectable-text').innerText;
} else {
return false;
}
}
function getUnreadChats(){
var unreadchats = [];
var chats = getElement("chats");
if (chats){
chats = chats.childNodes;
for (var i in chats){
if (!(chats[i] instanceof Element)){
continue;
}
var icons = getElement("chat_icons", chats[i]).childNodes;
if (!icons){
continue;
}
for (var j in icons){
if (icons[j] instanceof Element){
if (!(icons[j].childNodes[0].getAttribute('data-icon') == 'muted' || icons[j].childNodes[0].getAttribute('data-icon') == 'pinned')){
unreadchats.push(chats[i]);
break;
}
}
}
}
}
return unreadchats;
}
function didYouSendLastMsg(){
var messages = document.querySelectorAll('.msg');
if (messages.length <= 0){
return false;
}
var pos = messages.length-1;
while (messages[pos] && messages[pos].classList.contains('msg-system')){
pos--;
if (pos <= -1){
return -1;
}
}
if (messages[pos].querySelector('.message-out')){
return true;
}
return false;
}
// Call the main function again
const goAgain = (fn, sec) => {
// const chat = document.querySelector('div.chat:not(.unread)')
// selectChat(chat)
setTimeout(fn, sec * 1000)
}
// Dispath an event (of click, por instance)
const eventFire = (el, etype) => {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent(etype, true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
el.dispatchEvent(evt);
}
// Select a chat to show the main box
const selectChat = (chat, cb) => {
const title = getElement("chat_title",chat).title;
eventFire(chat.firstChild.firstChild, 'mousedown');
if (!cb) return;
const loopFewTimes = () => {
setTimeout(() => {
const titleMain = getElement("selected_title").title;
if (titleMain !== undefined && titleMain != title){
console.log('not yet');
return loopFewTimes();
}
return cb();
}, 300);
}
loopFewTimes();
}
// Send a message
const sendMessage = (chat, message, cb) => {
//avoid duplicate sending
var title;
if (chat){
title = getElement("chat_title",chat).title;
} else {
title = getElement("selected_title").title;
}
ignoreLastMsg[title] = message;
messageBox = document.querySelectorAll("[contenteditable='true']")[0];
//add text into input field
messageBox.innerHTML = message.replace(/ /gm,'');
//Force refresh
event = document.createEvent("UIEvents");
event.initUIEvent("input", true, true, window, 1);
messageBox.dispatchEvent(event);
//Click at Send Button
eventFire(document.querySelector('span[data-icon="send"]'), 'click');
cb();
}
//
// MAIN LOGIC
//
const start = (_chats, cnt = 0) => {
// get next unread chat
const chats = _chats || getUnreadChats();
const chat = chats[cnt];
var processLastMsgOnChat = false;
var lastMsg;
if (!lastMessageOnChat){
if (false === (lastMessageOnChat = getLastMsg())){
lastMessageOnChat = true; //to prevent the first "if" to go true everytime
} else {
lastMsg = lastMessageOnChat;
}
} else if (lastMessageOnChat != getLastMsg() && getLastMsg() !== false && !didYouSendLastMsg()){
lastMessageOnChat = lastMsg = getLastMsg();
processLastMsgOnChat = true;
}
if (!processLastMsgOnChat && (chats.length == 0 || !chat)) {
console.log(new Date(), 'nothing to do now... (1)', chats.length, chat);
return goAgain(start, 3);
}
// get infos
var title;
if (!processLastMsgOnChat){
title = getElement("chat_title",chat).title + '';
lastMsg = (getElement("chat_lastmsg", chat) || { innerText: '' }).innerText; //.last-msg returns null when some user is typing a message to me
} else {
title = getElement("selected_title").title;
}
// avoid sending duplicate messaegs
if (ignoreLastMsg[title] && (ignoreLastMsg[title]) == lastMsg) {
console.log(new Date(), 'nothing to do now... (2)', title, lastMsg);
return goAgain(() => { start(chats, cnt + 1) }, 0.1);
}
// what to answer back?
let sendText
if (lastMsg.toUpperCase().indexOf('#HELP') > -1){
sendText = `
Cool ${title}! Some commands that you can send me:
1. *#TIME*
2. *#JOKE*`
}
if (lastMsg.toUpperCase().indexOf('#About') > -1){
sendText = `
Cool ${title}! Some commands that you can send me:
*${new Date()}*`
}
if (lastMsg.toUpperCase().indexOf('#TIME') > -1){
sendText = `
Don't you have a clock, dude?
*${new Date()}*`
}
if (lastMsg.toUpperCase().indexOf('#JOKE') > -1){
sendText = jokeList[rand(jokeList.length - 1)];
}
// that's sad, there's not to send back...
if (!sendText) {
ignoreLastMsg[title] = lastMsg;
console.log(new Date(), 'new message ignored -> ', title, lastMsg);
return goAgain(() => { start(chats, cnt + 1) }, 0.1);
}
console.log(new Date(), 'new message to process, uhull -> ', title, lastMsg);
// select chat and send message
if (!processLastMsgOnChat){
selectChat(chat, () => {
sendMessage(chat, sendText.trim(), () => {
goAgain(() => { start(chats, cnt + 1) }, 0.1);
});
})
} else {
sendMessage(null, sendText.trim(), () => {
goAgain(() => { start(chats, cnt + 1) }, 0.1);
});
}
}
start();