Node.js Promise with mongoose - javascript

I have difficulty using Promise.
I want to get data from one more tables in mongodb.
but I fell in callback hell, So I tried to solve this but I couldn't.
What should I do? the result came out 'undefined'.
Many Thanks,
let mongoose = require('mongoose');
mongoose.Promise = global.Promise;
....
exports.Recommend = (id) => {
User.find({User_id: myId})
.then((result) => {
return Promise.resolve(result[0].age)
}).then(age => {
return new Promise((resolve,rejject)=>{
resolve(User.find()
.select('User_id')
.where('age').equals(age))
})
}).then((Users_id) => {
Users_id.forEach((user, idx, arr) => {
Count.find()
.select('board_id')
.where('User_id').equals(user.User_id)
.exec((err, items) => {
return new Promise((resolve,reject)=>{
resolve(
items.forEach((post, idx, arr) => {
posts.push(post.board_id)
}))
})
})
})
}).then(()=>{
console.log("posts:"+posts);
})
}

Avoid Promise.resolve, avoid using the new Promise constructor like Promise.resolve, avoid the Promise constructor antipattern, and avoid forEach, and don't forget to return the promise chain from your function:
exports.Recommend = (id) => {
return User.find({User_id: myId}).then(result => {
return User.find()
.select('User_id')
.where('age')
.equals(result[0].age));
}).then(user_ids => {
return Promise.all(user_ids.map((user, idx, arr) => {
return Count.find()
.select('board_id')
.where('User_id').equals(user.User_id)
.exec()
.then(posts => posts.map(post => post.board_id));
}));
}).then(board_ids => {
console.log("posts:"+board_ids);
})
}

You have the problem with 3rd .then, I would like to recommend you to use Promise.all function to run the parallel database query. Following example may help you
exports.Recommend = (id) => {
User.find({
User_id: myId
})
.then((result) => {
return User.find()
.select('User_id')
.where('age').equals(result[0].age)
}).then((Users_id) => {
return Promise.all(Users_id.map((user, idx, arr) => {
return Count.find()
.select('board_id')
.where('User_id').equals(user.User_id)
}));
}).then((Users_id) => {
Users_id.forEach(items => {
items.forEach(post => {
posts.push(post.board_id)
})
})
}).then(() => {
console.log("posts:" + posts);
})
}

Related

How to create javascript promise chain with array function?

I am facing a weired issue when creating a js promise chain.In promise,when I am using array function with (),I don'nt get the expected value.It give me the 'undefined' value in second then.
Here is the js code:
let x = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('sonet970#gmail.com');
}, 2000);
});
function y(email) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(email);
}, 4000);
});
}
x.then((res) => {
y(res);
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
But when I didn't use the ()=>{} syntax inside the .then,I got the expected answer.
Here is the example of wright code:
let x = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('sonet970#gmail.com');
}, 2000);
});
function y(email) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(email);
}, 4000);
});
}
x.then((res) => y(res))
.then((res) => console.log(res))
.catch((err) => console.log(err));
Can anyone please help me with this issue?
In order to chain promises you need to return Promise.
This sample works correctly
x.then((res) => y(res))
.then((res) => console.log(res))
.catch((err) => console.log(err));
because (res) => y(res) means:
(res) => {
return y(res)
}
and the result of y() promise is passed to the next .then
So to solve your code you need to write it in this way:
x.then((res) => {
// do some calculations
return y(res);
})
.then((res) => {
// result of y promise
console.log(res);
})
.catch((err) => {
console.log(err);
});
Returning something from a function using curly braces {} means that you need to use keyword return to return something:
x.then((res) => {
return y(res);
});
Using arrow functions, if no curly braces added, the immediately value after => is returned.
then((res) => console.log(res));
Thank you all for your answers.Now I understand,why my first code din't work.It all about array function,nothing w
ith promises!

How to make two api calls using Promise.all within Angular9?

I making an api call using Promise.all as below:
Promise.all(this.hostName.slice(0, this.Id.length).map((hostName) => {
return this.serviceC.status(hostName)
.then(res => {
return new Promise((resolve, reject) => {
const oretry: ORInterface = {
oQid: res.rows[0].qid,
reason: this.reason
};
this.serviceB.retry(oretry).subscribe(resolve);
});
});
}))
.then(() => {
this.dialog.close();
})
.catch(err => {
console.log(err);
});
The above code is working fine.
Now I want to make another api call after the successful completion of this.serviceB.retry(oretry).
The second api is this.serviceB.createDbEntry(sentry) and sentry looks as below:
const sretry: SDInterface = {
hostName,
Id: this.Id.slice(0, this.Id.length),
reason: this.reason
};
And, I am doing it as below
Promise.all(this.hostName.slice(0, this.Id.length).map((hostName) => {
return this.serviceC.status(hostName)
.then(res => {
return new Promise((resolve, reject) => {
const oretry: ORInterface = {
oQid: res.rows[0].qid,
reason: this.reason
};
const sretry: SDInterface = {
hostName,
Id: this.Id.slice(0, this.Id.length),
reason: this.reason
};
this.serviceB.retry(oretry).subscribe(resolve);
this.serviceB.createDbEntry(sentry).subscribe(resolve);
});
});
}))
.then(() => {
this.dialog.close();
})
.catch(err => {
console.log(err);
});
The above code is giving an error:
error: "SequelizeValidationError: string violation: Id cannot be an array or an object"
It is looks like it is not calling the second api for every Id
You may want to take a look a forkJoin
import { Observable, forkJoin } from 'rxjs';
And then
ngOnInit() {
let one = this.http.get('some/api/1') //some observable;
let two = this.http.get('some/api/2') // another observable;
forkJoin([one, tow]).subscribe(response => {
// results[0] is our one call
// results[1] is our second call
let var1 = response[1];
let var2 = response[0];
}/*, error => { in case error handler } */);
}
Wouldn't it be better to use Promise.all() once more?
Promise.all(this.hostName.slice(0, this.Id.length).map((hostName) => {
return this.serviceC.status(hostName)
.then(res => {
return new Promise((resolve, reject) => {
const oretry: ORInterface = {
oQid: res.rows[0].qid,
reason: this.reason
};
this.serviceB.retry(oretry).subscribe(resolve);
});
})
.then(() => {
return Promise.all(this.Id.slice(0, this.Id.length).map(id => {
return new Promise((resolve, reject) => {
const sretry: SDInterface = {
hostName,
Id: id,
reason: this.reason
};
this.serviceB.createDbEntry(sentry).subscribe(resolve);
});
})
});
}))
.then(() => {
this.dialog.close();
})
.catch(err => {
console.log(err);
});
And using toPromise() will make the code more concise.
Promise.all(this.hostName.slice(0, this.Id.length).map((hostName) => {
return this.serviceC.status(hostName)
.then(res => {
const oretry: ORInterface = {
oQid: res.rows[0].qid,
reason: this.reason
};
return this.serviceB.retry(oretry).toPromise();
})
.then(() => {
return Promise.all(this.Id.slice(0, this.Id.length).map(id => {
const sretry: SDInterface = {
hostName,
Id: id,
reason: this.reason
};
this.serviceB.createDbEntry(sentry).toPromise();
})
});
}))
.then(() => {
this.dialog.close();
})
.catch(err => {
console.log(err);
});
Use combineLatest, in Angular we use RxJs not promises.
combineLatest(
[this.http.get('call1'), this.http.get('call2')]
).subscribe(([result1, result2]) => {
// do stuff with result1 and result2
});
promise.all takes input in an array and gives response in an array,
Create 2 functions each with your asynchronous logic returning a promise,
Say funcA and funcB, then use below to invoke them parellely
Promise.all([funcA(this.hostName), funcB(this.id)])
.then(respones => {
console.log(responses[0]); //return value for funcA
console.log(responses[1]); //return value for funcB
})
.catch(err => console.log(err));
I am assuming your logic of functions are correct, I just copy-pasted from your question and gave them structure
const funcA = (hostName) => {
hostName.slice(0, this.Id.length).map((hostName) => {
return this.serviceC.status(hostName)
.then(res => {
return new Promise((resolve, reject) => {
const oretry: ORInterface = {
oQid: res.rows[0].qid,
reason: this.reason
};
this.serviceB.retry(oretry).subscribe(resolve);
});
});
});
}
const funcB = (Id) => {
Id.slice(0, this.Id.length).map(id => {
return new Promise((resolve, reject) => {
const sretry: SDInterface = {
hostName,
Id: id,
reason: this.reason
};
this.serviceB.createDbEntry(sentry).subscribe(resolve);
});
})
}

How to use foreach and promise

I need to get datas with nested foreach, but I can't fill my array.
At the end of this code I would like to have an array (segId) with my datas but it is empty (because of aynschronous).
I read that I had to use Promise.all but I can't beacause my promise are nested
I'm beginner so my code is far from perfect
How can I do that ?
async function getActivities(strava, accessToken)
{
const payload = await strava.athlete.listActivities({'access_token':accessToken, 'after':'1595281514', 'per_page':'10'})
return payload;
}
async function getActivity(strava, accessToken, id)
{
const payload = await strava.activities.get({'access_token':accessToken, 'id':id, 'include_all_efforts':'true'})
return payload;
}
async function getSegment(strava, accessToken, id)
{
const payload = await strava.segments.get({'access_token':accessToken,'id':id})
return payload
}
var tableau = []
var segId = []
const activities = getActivities(strava, accessToken)
activities.then(value => {
value.forEach((element, index) => {
const activity = getActivity(strava, accessToken, element['id'])
activity.then(value => {
value['segment_efforts'].forEach((element, index) => {
const segment = getSegment(strava, accessToken, element['segment']['id'])
segment.then(value => {
segId.push(value['id'])
})
//console.log(segId)
});
});
})
}) console.log(segId)
Regards
PS : Sorry for my english ...
Something like this should work. You need to always return the inner promises to include them in your promise chain. Consider splitting the code into functions to make it more readable.
getActivities(strava, accessToken).then(activities => {
return Promise.all(activities.map(elem => {
return getActivity(strava, accessToken, elem['id']).then(activity => {
return Promise.all(activity['segment_efforts'].map(elem => {
return getSegment(strava, accessToken, elem['segment']['id']).then(segment => {
segId.push(segment['id']);
});
}));
})
}));
})
.then(_ => {
console.log(segId);
});

Do forEach async requests inside of a promise?

Need help related to promises. Please refer to details below, topic is more theoretical, I don't understand what flow should I use:
We have async function getDataFromUri(), which returns data, which gets filtered and saved to arr of objects, lets name it res;
For each campaign(object) inside of array res I want send async request which will store products images of campaign to object. As result I should have ONE array res where ALL filtered data (campaign name, campaign images) is stored;
I need smth like:
[{
name: "Somename",
images: ['uri', 'uri', 'uri', 'uri', 'uri', 'uri']
},{
name: "Somename",
images: ['uri', 'uri', 'uri', 'uri', 'uri', 'uri']
}
]
Do some other actions with RES array.
This function gets campaigns:
function getDataFromUri(uri) {
return new Promise((resolve, reject) => {
request.get(uri, (err, res, body) => {
if(err || res.statusCode !== 200 ) {
reject(handleErr(err));
} else {
resolve(body);
}
});
});
}
This function gets images of campaign:
function getProductsOfCampaign(id) {
var productsImagesLinks = [];
return new Promise((resolve, reject) => {
getDataFromUri(`SOME_URI/${id}.json`)
.then((json) => {
var productsList = JSON.parse(json).products;
resolve (productsList.map((product) => product.imgSrc));
}).catch((e) => {
throw new Error(e);
})
});
}
Here I met problem:
getDataFromUri(someLink) //Get campaings;
.then((result) => {
//NOT WORKING FOREACH
result.forEach((item, i) => {
item.images = getProductsOfCampaign(item.id);
})
return result;
})
.then((result) => {
//Do something else to array with images;
});
How can I force next after forEach .then() expression to wait all images URLs to be saved?
I tried Promise.all(), but seems have lack of knowledge on how to implement it correct way.
I will really appreciate if you help me resolve this case. Thank you.
Observe that:
item in forEach is a copy.
getProductsOfCampaign returns a Promise.
The web is a best-effort service.
Do this:
getDataFromUri(someLink) // Get campaigns
.then(result => {
var promises = result.map(item =>
getProductsOfCampaign(item.id)
.then(products => {
item.images = products;
return item;
})
// 3: Best-effort service
.catch(() => {})
);
return Promise.all(promises);
}).then(items => {
console.log(items);
// Do something else to array of items with images
});
Other readers can test for correctness with this:
function getDataFromUri(someLink) {
return new Promise((resolve) => {
setTimeout(resolve, 1000, [{id: 1}, {id: 2}]);
})
}
function getProductsOfCampaign(id) {
return new Promise((resolve) => {
setTimeout(resolve, 1000, id * id);
})
}
var someLink = '';
Thanks to Benjamin Gruenbaum for suggesting that .catch(() => {}) can be used with Promise.all for a best-effort service.
let campaigns = null;
getDataFromUri(someLink) //Get campaings;
.then((result) => {
campaigns = result;
let pImages = []
result.forEach((item, i) => {
pImages.push(getProductsOfCampaign(item.id));
});
return Promise.all(pImages);
})
.then((images) => {
campaigns.forEach((campaign, index) => {
campaign.images = images[index];
});
// ... Do something else to array with images;
});

How to nested promise.all

I'm using es6 and have the following promises. What i want is the next Promise.all to wait for previous Promise.all to be completed before execute the next one. I have tried with the below codes but it's not working, only Promise 1 is resolved.
var deletePromises = [];
arr.menuItems.forEach((item, idx) => {
if (item.replace) {
deletePromises.push(deleteFromFirebase(user.uid, item));
}
});
// Promise 1
Promise.all(deletePromises).then(res1 => {
var uploadPromises = [], updateRecordPromises = [];
arr.menuItems.forEach((item, idx) => {
uploadPromises.push(uploadToFirebase(user.uid, item));
});
// Promise 2
Promise.all(uploadPromises).then(res2 => {
arr.menuItems.forEach((item, idx) => {
item.replace = false;
updateRecordPromises.push(updateRecord(user.uid, item));
});
// Promise 3
Promise.all(updateRecordPromises).then(res3 => {
console.log('All promise execute with successfully');
});
});
});
MarkM Answer
Try to use chaining as Mark suggest but the problem still there. I had found where the problem was, it is uploadPromises that never get resolved and then is never get called.
uploadToFirebase function
Stuck here, but the file is successfully uploaded. I can see all the files.
const uploadToFirebase = (userid, item) => {
return new Promise((resolve, reject) => {
const uploadUri = Platform.OS === "ios"
? RNFetchBlob.wrap(item.pic_url.replace("file://", ""))
: RNFetchBlob.wrap(item.pic_url);
Blob.build(uploadUri, {
type: "image/png;"
}).then(blob => {
// upload image using Firebase SDK
firebase
.storage()
.ref("menu_items")
.child(userid)
.child(item.new_filename)
.put(blob, { contentType: "image/png" })
.then(snapshot => {
console.log("Promise resolve: ", snapshot);
resolve(snapshot);
blob.close();
})
.catch(error => {
reject(error.message);
});
});
});
};
Updated code
console.log('Print res2') is not printed
var deletePromises = [],
uploadPromises = [],
updateRecordPromises = [];
arr.menuItems.forEach((item, idx) => {
if (item.replace) {
deletePromises.push(deleteFromFirebase(user.uid, item));
}
});
Promise.all(deletePromises)
.then(res1 => {
console.log("Print res1:", res1);
arr.menuItems.forEach((item, idx) => {
uploadPromises.push(uploadToFirebase(user.uid, item));
});
return Promise.all(uploadPromises);
})
.then(res2 => {
console.log("Print res2:", res2);
dispatch({ type: MENU_UPDATE_SUCCESS, payload: arr });
dispatch(reset("menuItem"));
})
.catch(error => {
console.log("Print error:", error);
});
You don't need to nest the Promises, you can return your new Promise.all from then(), which will let you chain them. Easier with an example:
var arr = [1, 2, 3, 4, 5, 6]
function slowF(i) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(i), i*200)
})
}
var p = arr.map((i) => slowF(i))
Promise.all(p)
.then((p) => {
console.log("In first Promise.all resolving: ", p)
var newP = p.map(i => slowF(i) )
return Promise.all(newP)
})
.then((p)=>{
console.log("In second Promise.all resolving: ", p)
})
.catch((e) => console.log("error: ", e))
I found the solution. It is because one of menuItems array prop -> new_filename is empty, thats why promise never get resolved. So, i just need to add empty checking for each of item prop and then the promise was resolved properly. Thanks to #MarkM for the answer. Now the code much more cleaner and easier to read compare to the nested promise.
Promise.all(deletePromises)
.then(res1 => {
console.log("Print res1:", res1);
arr.menuItems.forEach((item, idx) => {
if (!isEmpty(item.new_filename)) {
uploadPromises.push(uploadToFirebase(user.uid, item));
}
});
return Promise.all(uploadPromises);
})
.then(res2 => {
console.log("Print res2:", res2);
dispatch({ type: MENU_UPDATE_SUCCESS, payload: arr });
dispatch(reset("menuItem"));
})
.catch(error => {
console.log("Print error:", error);
});

Categories