Reputation: 3278
I know it is a simple, dumb question but it's been two days since I'm stuck on it.
Consider there is a function, managing creation of object type Course
from some object type UnsafeCourse
, like so:
Class Schedule {
constructor() {
this.courses = [];
}
sectionNeedsCourse(unsafeCourse) {
this.courses.forEach(function (course, index, array) {
if (course.couldBeRepresentedBy(unsafeCourse)) {
return course;
}
}
return new Course(unsafeCourse, [some additional parameters...]);
}
}
As things in node.js works asynchronously, for loop is gone-through.
I tried different approaches with Promise
s, didn't work.
sectionNeedsCourse(unsafeCourse) { //-> Promise
return new Promise (function (resolve) {
new Promise(function (resolve) {
this.courses.forEach(function (course, index, array) {
if (course.couldBeRepresentedBy(unsafeCourse)) {
resolve(eachCourse);
}
});
resolve(null);
}).then(function (result) {
console.log(result);
if (result != null) {
addCourse(unsafeCourse).then(function (result) {
resolve(result);
});
} else {
resolve(result);
}
});
});
}
Also, is it a good practice to use multiple Promise
s in same function?
Does it make heavy overhead?
Upvotes: 0
Views: 87
Reputation: 1156
I can't see any async method in your first example. Array.forEach
is not a async function.
You just return the course inside of the callback of forEach, but you must return it directly in sectionNeedsCourse
:
sectionNeedsCourse(unsafeCourse) {
var course = this.courses.find(function(course){
course.couldBeRepresentedBy(unsafeCourse) ? course : false;
});
return course ? course : new Course(unsafeCourse, []);
}
As you can see, i also use find
instead of forEach
, because this is the logic you need here.
As requested here the same example a little bit shorter with an Arrow function:
sectionNeedsCourse(unsafeCourse) {
var course = this.courses.find(course => {
course.couldBeRepresentedBy(unsafeCourse) ? course : false;
});
return course ? course : new Course(unsafeCourse, []);
}
Upvotes: 2