Multiple similar inserts using promise.all

Typically, my pages make use of custom providers I inject, the providers typically have a few helper functions. I am working on an app where I will insert a number of similar rows into a database, so I plan on using promise.all
Following the many examples, I create an array and then map it into a reference to the function I call which exists in a class instance named myprovider, such as

		// inject provider into ctor named myprovider
		// build array named myarray

		let maparray:any = Promise.all(myarray.map(this.myprovider.dosomething));
		maparray.then ... etc

Works fine ion simple testbeds, except when the app goes to this.myprovider.dosomething, all of the helper functions, class members, etc are undefined. The ctor never fires.

Any good ideas on making members of a class in a referenced function visible?

try using another variable for “this”

let localThis = this;
let maparray:any = Promise.all(myarray.map(localThis.myprovider.dosomething));

I prefer to always use a closure in situations like this:

let maparray = Promise.all(myarray.map(thingy => this.myprovider.dosomething(thingy)));

Not only does it solve the execution context problem you are running into, I find it far easier to read, because thingy is explicitly written out (giving you a chance to give it a more descriptive name than “thingy”). I always want my functions to be given arguments; I dislike using them as mere barewords.

Incidentally, I would refactor this to have all the Promise stuff happen within the provider. Presumably the pseudocode you write here is intended to go in a page. I don’t think pages should be concerning themselves with such minutia of data management: that should be strictly the providers` job.

Excellent, thanks so much. Im not sure if I understand what is happening: does the fat arrow allow the context to come over to dosomething()?

p.s. agree that mythingy is not descriptive. Planning on using TakingTooLong or SavedByRapropos.

Yes. Basically, you should never use this. There are now much clearer ways to code JS.

Thanks Aaron. Care to share?

I have no idea what you’re asking. But you could start by reading about the fat arrow and ES6.

Here’s FMTEYWTK on the topic.

By this are you referring to the javascript “this” keyword, or this