I am building a Chrome Extension that does Speach-to-Text to a Google Document. In my service-worker I am receiving the processed text (via port messaging, so is periodic), so it can be sent to be written but I can also receive commands if the user wants to insert a new paragraph, create a bullet list, etc. When I recieve a command I have a function that manages it checkCommand(currCommand);
that looks like this:
const checkCommand = (cmd) => {
const commands = {
'foo command': () => {
console.log('This command should create a bullet list');
if(currListType !== null){
callGoogleAPIScript(myToken, 'createBulletList',currListType);
formatingMode = false;
}
},
'bar command': () => {
console.log('This command should create a new paragraph');
callGoogleAPIScript(myToken, 'newParagraph');
formatingMode = false;
},
};
if (cmd && commands.hasOwnProperty(cmd)) {
commands[cmd](); // needed [cmd] because split words
} else {
console.log('Command dosen't exist');
formatingMode = false;
}};
Note: formatingMode is used for the service-worker to know that the command has been executed and can continue dictation.
While formatingMode !== false, I am still receiving text, but now I want to set specific characteristics for my commands, for example, currListType that tells which bullet list the user chose (circle, number, etc.). How can I wait for this variable to be set in the program and then run callGoogleAPIScript(myToken, ‘createBulletList’,currListType);?
I’ve tried using a promise right before calling callGoogleAPIScript , something like this:
function waitUntilListTypeSet() {
return new Promise((resolve, reject) => {
const checkListType = () => {
if (currListType !== null) {
resolve();
} else {
setTimeout(checkListType, 100);
}
};
try {
checkListType();
} catch (error) {
reject(error);
}
});
}
But from what I’ve read setTimeout is unreliable in service-worker + it doesn’t work for some reason ( my currListType is set correctly globally, but promise blocks)