I'm having lots of trouble combining a for loop with promises. In essence, my workflow is:
- Take an array of
Artist
objects in Node.js, and grab their biographies and IDs using Mongoose. - Use their IDs to get all the artwork (more specifically, all the artwork keywords) created by that artist.
- Train them in a natural language processor classifier (this part
isn't super relevant- just know that I need to have access to
biography
andkeywords
within the same outer scope.
However, I can't seem to use the bioText
object inside the Mongoose promise, and I can't seem to return the keywords from the Mongoose promise.
if (!isBlank(bioText) && bioText){
bioText = artist.BIO;
artworkIdArray.forEach((id)=> {
console.log(bioText) // <- prints correct values
var getKey = function(){
var words = Artwork.findById(id).then((artwork)=>{
console.log(bioText) // <- empty string
if(artwork.artworkKeywords.length > 0){
keywords = artwork.artistKeywords;
return keywords;
}
}
)
return words;
}
t=getKey();
t.then((t)=>{
console.log(t); // <--- always undefined
})
}, this);
}
As you can see, I try to console.log()
after exiting the promise, but the t
object is always undefined.
Additionally,
I know that in my example bioText
is available right up until the Mongoose find()
promise. But I also don't know how to inject bioText
into the promise (because then I could simply just train the classifier inside the then()
statement.
So my post is basically two questions:
- Can Promises use outside variables inside
then()
? - How do I return a variable declared inside
then()
so it is available in the outer scope?