Reputation: 1929
I'm trying to return an object with a specific structure but i can't return the object.
As you can see in the code if i print inside promise it prints data but if i print outside is empty... why?
How can i return the object parts?
var parts = [];
var part = [];
var articles = [];
part.push(request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'"));
return Promise.all([Promise.all(part)]).then(function(listOfResults)
{
for(var i=0; i<listOfResults[0][0].length; i++)
{
articles.push(request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+listOfResults[0][0][i].u_order+"'"));
//articles.push(request.query("SELECT ststamp, ref, design FROM st (nolock) WHERE u_posic = '"+listOfResults[0][0][i].u_order+"'"));
Promise.all([Promise.all(articles)]).then(function(listOfArticles)
{
for(var j=0; j<listOfResults[0][0].length; j++)
{
parts.push({
u_order: listOfResults[0][0][j].u_order,
u_familia: listOfResults[0][0][j].u_familia,
u_part: listOfResults[0][0][j].u_part,
u_type: listOfResults[0][0][j].u_type,
articles: listOfArticles[0][j-1]
});
console.log(parts); HERE THE OBJECT HAD DATA
}
});
}
console.log(parts); BUT HERE IS EMPTY
}).catch(function(err)
{
console.log(err);
});
Thank you.
Upvotes: 3
Views: 1900
Reputation: 10532
The whole point of Promises
is being asynchronous. You need to wait for your Promise to resolve
or reject
to check for data. Specifically, you should only do anything with the returned value of your Promise
within the Promise.then()
method, which runs as soon as the Promise
finishes execution. Changing variables which exist outside the Promise
from within it, as you are doing by calling parts.push()
is a bad practice. You should return parts
within your promise, and then, in a final .then()
callback, you should do whatever is required with parts
.
Something like:
Promise.all(part).then(makeAllQueries).then(doSomethingWithQueryResults);
You can only be sure you actually have data or not when your final .then
callback runs.
Also, doing Promise.all([Promise.all(part)])
does nothing for you, as you're just wrapping your returned array in one more array level.
Upvotes: 3