I'm learning work with promises and i want to select data from a table and add this to an array and send this array to next then.
I do this but it return [Promise {<pending>}]
:
var p1 = new Promise(function(resolve, reject) {
var stamp = req.params.stamp;
var part = [];
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'"));
resolve(part);
// or
// reject ("Error!");
});
p1.then(function(value){
console.log(value);
}, function(reason){
console.log(reason);
});
I think that i have to wait for promise but how?
UPDATE
Now i want to iterate the array part and do a select to another array. After that i have to create a new array with this stucture:
-PARTS
- part
- u_order
- u_familia
- u_part
- u_type
- articles (article from each part)
And i try this but cannot access to array articles
var p1 = new Promise(function(resolve, reject) {
var stamp = req.params.stamp;
request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'").then((data)=>resolve(data));
// or
// reject ("Error!");
});
p1.then(function(value){
var stamp = req.params.stamp;
console.log(value.length);
for(var i= 0; i<value.length; i++)
{
console.log(value[i]);
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 = '"+value[i].u_order+"'").then((data)=>resolve(data));
}
}, function(reason){
console.log(reason);
});
p1.then(function(part, articles){
var parts = [];
console.log("PART: " +part.length);
for(var j= 0; j<part.length; j++)
{
console.log(part[j].u_order);
console.log(part[j].u_familia);
console.log(part[j].u_part);
console.log(part[j].u_type);
console.log(articles[j]);
};
});
Thank you
You can do the following:
var stamp = req.params.stamp;
var p1 = request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'");
p1.then((value) => {
console.log(value.length);
var promise_arr = [];
for(var i= 0; i<value.length; i++)
{
console.log(value[i]);
promise_arr.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 = '"+value[i].u_order+"'"));
}
//Since request.query returns a promise we need to resolve all of the promises using Promise.all
return Promise.all(promise_arr);
}, (reason) => {
console.log(reason);
}).then((part) => { //This is where you receive result form Promise.all
var parts = [];
console.log("PART: " +part.length);
for(var j= 0; j<part.length; j++)
{
console.log(part[j].u_order);
console.log(part[j].u_familia);
console.log(part[j].u_part);
console.log(part[j].u_type);
console.log(articles[j]);
};
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.