I'm having trouble running Promises in an array of arrays of objects.
I have a hardcoded example of some data
const page = [
[
{
id: 1,
text: 'sentence 1'
},
{
id: 2,
text: 'sentence 2'
}
],
[
{
id: 3,
text: 'sentence 3'
}
]
]
A function called getSentiment takes a string and returns a promise
function getSentiment (sentence) {
const rand = Math.random()
if (rand < 0.3) {
return Promise.resolve(-1)
} else if (rand < 0.6) {
return Promise.resolve(0)
} else {
return Promise.resolve(1)
}
}
Here is my code that maps this nested array that creates/adds a new key/property to the objects.
const resolvedPage = page
.map(line => line
.map(async sentence => {
sentence.sentiment = await getSentiment(sentence.text)
return sentence
}))
getSentiment is called with async/await to get the value and assign to sentiment property and then return the object.
When I run console.log(resolvedPage) I get this
[
[ Promise { <pending> }, Promise { <pending> } ],
[ Promise { <pending> } ]
]
The result I expect should look like this:
[
[
{
id: 1,
text: 'sentence 1',
sentiment: 0
},
{
id: 2,
text: 'sentence 2',
sentiment: -1
}
],
[
{
id: 3,
text: 'sentence 3',
sentiment: 1
}
]
]
I tried using Promise.all but I'm not sure how to do it since my data is nested in an outer array.