I am trying to understand how to correctly use Promises in JS and I stumbled on following issue.
How to correctly/efficiently/in best way pass value into then
function of Promise from this
variable?
I am developing back-end using Node.js, MongoDB and Mongoose and have Calendar model, which I am extending with method getFilteredIcal
. Right now I am storing this
into temporary variable calendar
so it would be accessible via closure from then
function, but I don't like this approach and also think it is a wrong one.
See my problem in code attached.
var Calendar = new mongoose.Schema({
url: String,
userId: mongoose.Schema.Types.ObjectId
});
Calendar.method.getFilteredIcal = function (respond) {
var fetch = require('node-fetch');
var icalCore = require('../tools/icalCore');
var calendar = this; // <-- I don't like this
fetch.Promise = require('bluebird');
fetch(calendar.url)
.then(icalCore.parseIcal)
.then(parsedIcal => { return icalCore.filterIcal(parsedIcal, calendar._id) }) // <-- I need Calendar ID here
.then(icalCore.icalToString)
.done(icalString => respond.text(icalString));
};