0

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));
};
AuHau
  • 135
  • 9

1 Answers1

3

Given that you are already using arrow functions, there is absolutely no need for this calendar variable that is closed over - arrow functions do resolve their this value lexically.

fetch(calendar.url)
.then(icalCore.parseIcal)
.then(parsedIcal => icalCore.filterIcal(parsedIcal, this._id))
//                                                  ^^^^
.then(icalCore.icalToString)
.done(icalString => respond.text(icalString));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Hmm I see and I have to admit that I forgot about this, but now when I think about it, since I am using bluebird and not native Promises, won't be this in context of of bluebird's Promise? I have to try it out :-) – AuHau Nov 04 '15 at 17:37
  • No, the arrow function is a language feature. It doesn't matter which promise implementation you use. – Bergi Nov 04 '15 at 18:03
  • I see! I just test it and it worked! Thanks! :-) – AuHau Nov 04 '15 at 19:01