I'm new handling promises in javascript and I've found a problem with this node js lib https://www.npmjs.com/package/wordpos I'm trying to find all the verbs that are found inside an arrays of strings, and for this I've created this function:
function calculateVerbsAmount(stringsArray) {
return stringsArray.map(function(item) {
let element = wordpos.getVerbs(item, function(result){
return result;
});
});
}
What I expect is to have a new array, this time of verb strings, but since the lib handles the methods as callbacks I'm getting
[Promise { <pending> }, Promise { <pending> },
Promise { <pending> }, Promise { <pending> },
Promise { <pending> }, Promise { <pending> }]
I've tried added async/await but they always return the same result, any idea on how to do some synchronous call to the wordpos.getVerbs method?
Calling wordpos.getVerbs() returns a promise. Since you are doing this inside a .map function your stringsArray will be an array of promises (as you actually get as return.).
A single Promise can be unwraped using await. For an array of Promises you can use Promise.all helper which allows waiting for each Promise within an array.
async function calculateVerbsAmount(stringsArray) {
const verbPromises = stringsArray.map(function(item) {
let element = wordpos.getVerbs(item, function(result){
return result;
});
});
// await every Promise within the verbPromises array. Promise.all
// returns a single Promise which holds an array with the native values
return Promise.all(verbPromises)
}
// the keyword "await" can only be used within an async function.
// So for showcasing it i created the main() function ..
async function main() {
// Now call the calculateVerbsAmount() and await it for receiving the expected
// array of strings.
const verbs = await calculateVerbsAmount()
}