-3

I'm just trying to convert this to a normal js function without the "fat arrow".

I want body => to be a normal function.

How do I write that?

snippet from code

fetch(this.JobExecEndpoint)
  .then(response => response.json())
  .then(body => {
    this.cleanStartTime = moment(body[0].time_start);
    this.cleanEndTime = moment(body[0].time_end);
    this.cleanDuration = this.calculateDuration(
      this.cleanStartTime,
      this.cleanEndTime
    );
benjaminadon
  • 143
  • 3
  • 13

1 Answers1

0

// Hold a reference to "this" object inside a variable else you won't be able to access it using the "this" inside the callback function

var that = this; 

fetch(this.JobExecEndpoint).then(function(response)
{
     return response.json();
})
.then(function(body)
{
    that.cleanStartTime = moment(body[0].time_start);
    that.cleanEndTime   = moment(body[0].time_end);
    that.cleanDuration  = that.calculateDuration (
        that.cleanStartTime,
        that.cleanEndTime
    );
});

I hope this helps, let me know if you have any question :)

Zahid Saeed
  • 152
  • 2
  • 9
  • What's the point of `var that = this` when you can just do `function(body){}.bind(this)`? – meyi Jul 01 '19 at 20:34
  • You can do that as well. The syntax will just change a little bit. That's total up to you. If you use this method then you will need to use `.bind(this)` on each of the `.then()` function where was `var that = this` relieves you from this problem and you can continue chaining as long as you like :) – Zahid Saeed Jul 01 '19 at 20:36
  • @meyi Using `bind()` ends up being considerably slower execution. At least it did the last time I ran a performance test on it; it could have changed. Thus, if you can avoid using `.bind()` (without significant inconvenience), it's better to just use a variable. – Makyen Jul 02 '19 at 02:20