0
I have a primary function that makes calls from other functions within itself, functions that are called have return with callback as shown in the code below
async function processarFrase(frase) {
frase = limpezaInicial(frase);
let fraseOriginal = frase;
if (frase.match(regexes[0])) {
let match = await limpeza(frase);
frase = match;
}
getDictionary(frase, dictionary => {
let grupo = capturarGrupo(fraseOriginal, dictionary);
console.log(fraseOriginal);
console.log("Inserir isso no banco, no campo dataset: " + grupo);
console.log("\n");
});
}
what needs is that the main function that is the processrFrase returns the variable group because I need to access this variable in another scope, I tried this way below:
async function processarFrase(frase) {
let group;
frase = limpezaInicial(frase);
let fraseOriginal = frase;
if (frase.match(regexes[0])) {
let match = await limpeza(frase);
frase = match;
}
getDictionary(frase, dictionary => {
let grupo = capturarGrupo(fraseOriginal, dictionary);
console.log(fraseOriginal);
console.log("Inserir isso no banco, no campo dataset: " + grupo);
console.log("\n");
group = grupo;
});
return group;
}
But without success, if I do
let grupo = processarFrase("Uma frase qualquer");
and give a
console.log(grupo)
the result is
Undefined
how do I so that the main function can return to the group variable?
Parentheses are missing between getDictionary parameters. Try this way:
getDictionary((frase, dictionary), => { } )
– Murilo Ribas
I don’t understand very well: you are trying to declare or call the getDictionary function?
– Murilo Ribas
It does not need parentheses ,and what is needed is for the function to process Rase , returns that variable called group . the group variable is declared inside the getDictionary callback, so I created a variable called group to store what you have in group
– Israell Llopes
Ever tried to use
await
before callingcapturarGrupo
? post the function codecapturarGrupo
, please.– Murilo Ribas
Yes, I tried but I didn’t succeed
– Israell Llopes
the complete code in the Pastebin https://pastebin.com/3YmycrWC
– Israell Llopes
Why are you using callback if function
getDictionary
is asynchronous? has tried using the.then
?– Murilo Ribas
I didn’t try, I’d be like?
– Israell Llopes
I believe you’re wearing
async
andawait
wrong way, for example:await words.forEach(async palavra
Particularly, I have always seen the use of both words in http/database requests, never with something different. Try to remove words from your codeasync
andawait
places where you don’t need to use them. I hope this is it.– Murilo Ribas
In fact, it’s not right to use
async
before a variable (example:async palavra
). If you would like to see more content about: https://answall.com/questions/211505/como-posso-usuo-async-await-do-javascript– Murilo Ribas