Asynchronous operations in constructor - javascript

Hey I have question about prototype and inheretience in functions. Could you explan me how I can return arr from constructor and add this arr to prototype?
var example = new Constructor()
function Constructor(){
Service.getService().then(function(data){
this.arr = data.data.array;
return this.arr
})
}
Constructor.prototype.getArray = function(){
console.log(this.arr)
})
example.getArray();
And in getArray this.arr is undefined. Service and getService() are angular factory and connection between front and back-end

It is particularly difficult to put asynchronous operations in a constructor. This is for several reasons:
The constructor needs to return the newly created object so it can't return a promise that would tell you when the async operation is done.
If you do an asynchronous operation inside the constructor that sets some instance data and the constructor returns the object, then you have no way for the calling code to know when the async operation is actually done.
For these reasons, you usually don't want to do an async operation inside a constructor. IMO, the cleanest architecture below is the factory function that returns a promise that resolves to your finished object. You can do as much asynchronous stuff as you want in the factory function (call any methods on the object) and you don't expose the object to the caller until it is fully formed.
These are some of the various options for dealing with that issue:
Use Factory Function that Returns a Promise
This uses a factory function that does some of the more common work for you. It also doesn't reveal the new object until its fully initialized which is a good programming practice as the caller can't accidentally try to use a partially formed object in which the asynchronous stuff hasn't finished yet. The factory function option also cleanly propagates errors (either synchronous or asynchronous) by rejecting the returned promise:
// don't make this class definition public so the constructor is not public
class MyObj() {
constructor(someValue) {
this.someProp = someValue;
}
init() {
return Service.getService().then(val => {
this.asyncProp = val;
return this;
});
}
}
function createMyObj(someValue) {
let x = new MyObj(someVal);
return x.init();
}
createMyObj(someVal).then(obj => {
// obj ready to use and fully initialized here
}).catch(err => {
// handle error here
});
If you're using modules, you can export only the factory function (no need to export the class itself) and thus enforce that the object is initialized properly and not used until that initialization is done.
Break async object initialization into a separate method that can return a promise
class MyObj() {
constructor(someValue) {
this.someProp = someValue;
}
init() {
return Service.getService().then(val => {
this.asyncProp = val;
});
}
}
let x = new MyObj(someVal);
x.init().then(() => {
// ready to use x here
}).catch(err => {
// handle error
});
Use Events to Signal Completion
This scheme is used in a lot of I/O related APIs. The general idea is that you return an object from the constructor, but the caller knows that object hasn't really completed its initialization until a particular event occurs.
// object inherits from EventEmitter
class MyObj extends EventEmitter () {
constructor(someValue) {
this.someProp = someValue;
Service.getService().then(val => {
this.asyncProp = val;
// signal to caller that object has finished initializing
this.emit('init', val);
});
}
}
let x = new MyObj(someVal);
x.on('init', () => {
// object is fully initialized now
}).on('error', () => {
// some error occurred
});
Hackish way to put the Async Operation in the Constructor
Though I wouldn't recommend using this technique, this is what it would take to put the async operation in the actual constructor itself:
class MyObj() {
constructor(someValue) {
this.someProp = someValue;
this.initPromise = Service.getService().then(val => {
this.asyncProp = val;
});
}
}
let x = new MyObj(someVal);
x.initPromise.then(() => {
// object ready to use now
}).catch(err => {
// error here
});
Note, you see the first design pattern in many places in various APIs. For example, for a socket connection in node.js, you would see this:
let socket = new net.Socket(...);
socket.connect(port, host, listenerCallback);
The socket is created in the first step, but then connected to something in the second step. And, then the same library has a factory function net.createConnection() which combines those two steps into one function (an illustration of the second design pattern above). The net module examples don't happen to use promises (very few nodejs original apis do), but they accomplish the same logic using callbacks and events.
Other note on your code
You likely also have an issue with the value of this in your code. A .then() handler does not naturally preserve the value of this from the surrounding environment if you pass it a regular function() {} reference. So, in this:
function Constructor(){
Service.getService().then(function(data){
this.arr = data.data.array;
return this.arr
})
}
The value of this when you try to do this.arr = data.data.array; is not going to be correct. The simplest way to fix that issue in ES6 is to use a fat arrow function instead:
function Constructor(){
Service.getService().then(data => {
this.arr = data.data.array;
return this.arr
});
}

Related

Async function call inside a constructor in javascript class [duplicate]

At the moment, I'm attempting to use async/await within a class constructor function. This is so that I can get a custom e-mail tag for an Electron project I'm working on.
customElements.define('e-mail', class extends HTMLElement {
async constructor() {
super()
let uid = this.getAttribute('data-uid')
let message = await grabUID(uid)
const shadowRoot = this.attachShadow({mode: 'open'})
shadowRoot.innerHTML = `
<div id="email">A random email message has appeared. ${message}</div>
`
}
})
At the moment however, the project does not work, with the following error:
Class constructor may not be an async method
Is there a way to circumvent this so that I can use async/await within this? Instead of requiring callbacks or .then()?
This can never work.
The async keyword allows await to be used in a function marked as async but it also converts that function into a promise generator. So a function marked with async will return a promise. A constructor on the other hand returns the object it is constructing. Thus we have a situation where you want to both return an object and a promise: an impossible situation.
You can only use async/await where you can use promises because they are essentially syntax sugar for promises. You can't use promises in a constructor because a constructor must return the object to be constructed, not a promise.
There are two design patterns to overcome this, both invented before promises were around.
Use of an init() function. This works a bit like jQuery's .ready(). The object you create can only be used inside its own init or ready function:
Usage:
var myObj = new myClass();
myObj.init(function() {
// inside here you can use myObj
});
Implementation:
class myClass {
constructor () {
}
init (callback) {
// do something async and call the callback:
callback.bind(this)();
}
}
Use a builder. I've not seen this used much in javascript but this is one of the more common work-arounds in Java when an object needs to be constructed asynchronously. Of course, the builder pattern is used when constructing an object that requires a lot of complicated parameters. Which is exactly the use-case for asynchronous builders. The difference is that an async builder does not return an object but a promise of that object:
Usage:
myClass.build().then(function(myObj) {
// myObj is returned by the promise,
// not by the constructor
// or builder
});
// with async/await:
async function foo () {
var myObj = await myClass.build();
}
Implementation:
class myClass {
constructor (async_param) {
if (typeof async_param === 'undefined') {
throw new Error('Cannot be called directly');
}
}
static build () {
return doSomeAsyncStuff()
.then(function(async_result){
return new myClass(async_result);
});
}
}
Implementation with async/await:
class myClass {
constructor (async_param) {
if (typeof async_param === 'undefined') {
throw new Error('Cannot be called directly');
}
}
static async build () {
var async_result = await doSomeAsyncStuff();
return new myClass(async_result);
}
}
Note: although in the examples above we use promises for the async builder they are not strictly speaking necessary. You can just as easily write a builder that accept a callback.
Note on calling functions inside static functions.
This has nothing whatsoever to do with async constructors but with what the keyword this actually mean (which may be a bit surprising to people coming from languages that do auto-resolution of method names, that is, languages that don't need the this keyword).
The this keyword refers to the instantiated object. Not the class. Therefore you cannot normally use this inside static functions since the static function is not bound to any object but is bound directly to the class.
That is to say, in the following code:
class A {
static foo () {}
}
You cannot do:
var a = new A();
a.foo() // NOPE!!
instead you need to call it as:
A.foo();
Therefore, the following code would result in an error:
class A {
static foo () {
this.bar(); // you are calling this as static
// so bar is undefinned
}
bar () {}
}
To fix it you can make bar either a regular function or a static method:
function bar1 () {}
class A {
static foo () {
bar1(); // this is OK
A.bar2(); // this is OK
}
static bar2 () {}
}
You can definitely do this, by returning an Immediately Invoked Async Function Expression from the constructor. IIAFE is the fancy name for a very common pattern that was required in order to use await outside of an async function, before top-level await became available:
(async () => {
await someFunction();
})();
We'll be using this pattern to immediately execute the async function in the constructor, and return its result as this:
// Sample async function to be used in the async constructor
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
class AsyncConstructor {
constructor(value) {
return (async () => {
// Call async functions here
await sleep(500);
this.value = value;
// Constructors return `this` implicitly, but this is an IIFE, so
// return `this` explicitly (else we'd return an empty object).
return this;
})();
}
}
(async () => {
console.log('Constructing...');
const obj = await new AsyncConstructor(123);
console.log('Done:', obj);
})();
To instantiate the class, use:
const instance = await new AsyncConstructor(...);
For TypeScript, you need to assert that the type of the constructor is the class type, rather than a promise returning the class type:
class AsyncConstructor {
constructor(value) {
return (async (): Promise<AsyncConstructor> => {
// ...
return this;
})() as unknown as AsyncConstructor; // <-- type assertion
}
}
Downsides
Extending a class with an async constructor will have a limitation. If you need to call super in the constructor of the derived class, you'll have to call it without await. If you need to call the super constructor with await, you'll run into TypeScript error 2337: Super calls are not permitted outside constructors or in nested functions inside constructors.
It's been argued that it's a "bad practice" to have a constructor function return a Promise.
Before using this solution, determine whether you'll need to extend the class, and document that the constructor must be called with await.
Because async functions are promises, you can create a static function on your class which executes an async function which returns the instance of the class:
class Yql {
constructor () {
// Set up your class
}
static init () {
return (async function () {
let yql = new Yql()
// Do async stuff
await yql.build()
// Return instance
return yql
}())
}
async build () {
// Do stuff with await if needed
}
}
async function yql () {
// Do this instead of "new Yql()"
let yql = await Yql.init()
// Do stuff with yql instance
}
yql()
Call with let yql = await Yql.init() from an async function.
Unlike others have said, you can get it to work.
JavaScript classes can return literally anything from their constructor, even an instance of another class. So, you might return a Promise from the constructor of your class that resolves to its actual instance.
Below is an example:
export class Foo {
constructor() {
return (async () => {
// await anything you want
return this; // Return the newly-created instance
})();
}
}
Then, you'll create instances of Foo this way:
const foo = await new Foo();
The stopgap solution
You can create an async init() {... return this;} method, then instead do new MyClass().init() whenever you'd normally just say new MyClass().
This is not clean because it relies on everyone who uses your code, and yourself, to always instantiate the object like so. However if you're only using this object in a particular place or two in your code, it could maybe be fine.
A significant problem though occurs because ES has no type system, so if you forget to call it, you've just returned undefined because the constructor returns nothing. Oops. Much better would be to do something like:
The best thing to do would be:
class AsyncOnlyObject {
constructor() {
}
async init() {
this.someField = await this.calculateStuff();
}
async calculateStuff() {
return 5;
}
}
async function newAsync_AsyncOnlyObject() {
return await new AsyncOnlyObject().init();
}
newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}
The factory method solution (slightly better)
However then you might accidentally do new AsyncOnlyObject, you should probably just create factory function that uses Object.create(AsyncOnlyObject.prototype) directly:
async function newAsync_AsyncOnlyObject() {
return await Object.create(AsyncOnlyObject.prototype).init();
}
newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}
However say you want to use this pattern on many objects... you could abstract this as a decorator or something you (verbosely, ugh) call after defining like postProcess_makeAsyncInit(AsyncOnlyObject), but here I'm going to use extends because it sort of fits into subclass semantics (subclasses are parent class + extra, in that they should obey the design contract of the parent class, and may do additional things; an async subclass would be strange if the parent wasn't also async, because it could not be initialized the same way):
Abstracted solution (extends/subclass version)
class AsyncObject {
constructor() {
throw new Error('classes descended from AsyncObject must be initialized as (await) TheClassName.anew(), rather than new TheClassName()');
}
static async anew(...args) {
var R = Object.create(this.prototype);
R.init(...args);
return R;
}
}
class MyObject extends AsyncObject {
async init(x, y=5) {
this.x = x;
this.y = y;
// bonus: we need not return 'this'
}
}
MyObject.anew('x').then(console.log);
// output: MyObject {x: "x", y: 5}
(do not use in production: I have not thought through complicated scenarios such as whether this is the proper way to write a wrapper for keyword arguments.)
Based on your comments, you should probably do what every other HTMLElement with asset loading does: make the constructor start a sideloading action, generating a load or error event depending on the result.
Yes, that means using promises, but it also means "doing things the same way as every other HTML element", so you're in good company. For instance:
var img = new Image();
img.onload = function(evt) { ... }
img.addEventListener("load", evt => ... );
img.onerror = function(evt) { ... }
img.addEventListener("error", evt => ... );
img.src = "some url";
this kicks off an asynchronous load of the source asset that, when it succeeds, ends in onload and when it goes wrong, ends in onerror. So, make your own class do this too:
class EMailElement extends HTMLElement {
connectedCallback() {
this.uid = this.getAttribute('data-uid');
}
setAttribute(name, value) {
super.setAttribute(name, value);
if (name === 'data-uid') {
this.uid = value;
}
}
set uid(input) {
if (!input) return;
const uid = parseInt(input);
// don't fight the river, go with the flow, use a promise:
new Promise((resolve, reject) => {
yourDataBase.getByUID(uid, (err, result) => {
if (err) return reject(err);
resolve(result);
});
})
.then(result => {
this.renderLoaded(result.message);
})
.catch(error => {
this.renderError(error);
});
}
};
customElements.define('e-mail', EmailElement);
And then you make the renderLoaded/renderError functions deal with the event calls and shadow dom:
renderLoaded(message) {
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.innerHTML = `
<div class="email">A random email message has appeared. ${message}</div>
`;
// is there an ancient event listener?
if (this.onload) {
this.onload(...);
}
// there might be modern event listeners. dispatch an event.
this.dispatchEvent(new Event('load'));
}
renderFailed() {
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.innerHTML = `
<div class="email">No email messages.</div>
`;
// is there an ancient event listener?
if (this.onload) {
this.onerror(...);
}
// there might be modern event listeners. dispatch an event.
this.dispatchEvent(new Event('error'));
}
Also note I changed your id to a class, because unless you write some weird code to only ever allow a single instance of your <e-mail> element on a page, you can't use a unique identifier and then assign it to a bunch of elements.
I usually prefer a static async method that returns a new instance, but here's another way to do it. It's closer to literally awaiting a constructor. It works with TypeScript.
class Foo {
#promiseReady;
constructor() {
this.#promiseReady = this.#init();
}
async #init() {
await someAsyncStuff();
return this;
}
ready() {
return this.promiseReady;
}
}
let foo = await new Foo().ready();
I made this test-case based on #Downgoat's answer.
It runs on NodeJS.
This is Downgoat's code where the async part is provided by a setTimeout() call.
'use strict';
const util = require( 'util' );
class AsyncConstructor{
constructor( lapse ){
this.qqq = 'QQQ';
this.lapse = lapse;
return ( async ( lapse ) => {
await this.delay( lapse );
return this;
})( lapse );
}
async delay(ms) {
return await new Promise(resolve => setTimeout(resolve, ms));
}
}
let run = async ( millis ) => {
// Instatiate with await, inside an async function
let asyncConstructed = await new AsyncConstructor( millis );
console.log( 'AsyncConstructor: ' + util.inspect( asyncConstructed ));
};
run( 777 );
My use case is DAOs for the server-side of a web application.
As I see DAOs, they are each one associated to a record format, in my case a MongoDB collection like for instance a cook.
A cooksDAO instance holds a cook's data.
In my restless mind I would be able to instantiate a cook's DAO providing the cookId as an argument, and the instantiation would create the object and populate it with the cook's data.
Thus the need to run async stuff into the constructor.
I wanted to write:
let cook = new cooksDAO( '12345' );
to have available properties like cook.getDisplayName().
With this solution I have to do:
let cook = await new cooksDAO( '12345' );
which is very similar to the ideal.
Also, I need to do this inside an async function.
My B-plan was to leave the data loading out of the constructor, based on #slebetman suggestion to use an init function, and do something like this:
let cook = new cooksDAO( '12345' );
async cook.getData();
which doesn't break the rules.
Use the async method in constructor???
constructor(props) {
super(props);
(async () => await this.qwe(() => console.log(props), () => console.log(props)))();
}
async qwe(q, w) {
return new Promise((rs, rj) => {
rs(q());
rj(w());
});
}
If you can avoid extend, you can avoid classes all together and use function composition as constructors. You can use the variables in the scope instead of class members:
async function buildA(...) {
const data = await fetch(...);
return {
getData: function() {
return data;
}
}
}
and simple use it as
const a = await buildA(...);
If you're using typescript or flow, you can even enforce the interface of the constructors
Interface A {
getData: object;
}
async function buildA0(...): Promise<A> { ... }
async function buildA1(...): Promise<A> { ... }
...
I found myself in a situation like this and ended up using an IIFE
// using TypeScript
class SomeClass {
constructor() {
// do something here
}
doSomethingAsync(): SomeClass {
(async () => await asyncTask())();
return this;
}
}
const someClass = new SomeClass().doSomethingAsync();
If you have other tasks that are dependant on the async task you can run them after the IIFE completes its execution.
A lot of great knowledge here and some super() thoughtful responses. In short the technique outlined below is fairly straightforward, non-recursive, async-compatible and plays by the rules. More importantly I don't believe it has been properly covered here yet - though please correct me if wrong!
Instead of method calls we simply assign an II(A)FE to an instance prop:
// it's async-lite!
class AsyncLiteComponent {
constructor() {
// our instance includes a 'ready' property: an IIAFE promise
// that auto-runs our async needs and then resolves to the instance
// ...
// this is the primary difference to other answers, in that we defer
// from a property, not a method, and the async functionality both
// auto-runs and the promise/prop resolves to the instance
this.ready = (async () => {
// in this example we're auto-fetching something
this.msg = await AsyncLiteComponent.msg;
// we return our instance to allow nifty one-liners (see below)
return this;
})();
}
// we keep our async functionality in a static async getter
// ... technically (with some minor tweaks), we could prefetch
// or cache this response (but that isn't really our goal here)
static get msg() {
// yes I know - this example returns almost immediately (imagination people!)
return fetch('data:,Hello%20World%21').then((e) => e.text());
}
}
Seems simple enough, how is it used?
// Ok, so you *could* instantiate it the normal, excessively boring way
const iwillnotwait = new AsyncLiteComponent();
// and defer your waiting for later
await iwillnotwait.ready
console.log(iwillnotwait.msg)
// OR OR OR you can get all async/awaity about it!
const onlywhenimready = await new AsyncLiteComponent().ready;
console.log(onlywhenimready.msg)
// ... if you're really antsy you could even "pre-wait" using the static method,
// but you'd probably want some caching / update logic in the class first
const prefetched = await AsyncLiteComponent.msg;
// ... and I haven't fully tested this but it should also be open for extension
class Extensior extends AsyncLiteComponent {
constructor() {
super();
this.ready.then(() => console.log(this.msg))
}
}
const extendedwaittime = await new Extensior().ready;
Before posting I had a brief discussion on the viability of this technique in the comments of #slebetman's comprehensive answer. I wasn't entirely convinced by the outright dismissal, so thought I would open it up to further debate / tear down. Please do your worst :)
You can use Proxy's construct handle to do this, the code like this:
const SomeClass = new Proxy(class A {
constructor(user) {
this.user = user;
}
}, {
async construct(target, args, newTarget) {
const [name] = args;
// you can use await in here
const user = await fetch(name);
// invoke new A here
return new target(user);
}
});
const a = await new SomeClass('cage');
console.log(a.user); // user info
Variation on the builder pattern, using call():
function asyncMethod(arg) {
function innerPromise() { return new Promise((...)=> {...}) }
innerPromise().then(result => {
this.setStuff(result);
}
}
const getInstance = async (arg) => {
let instance = new Instance();
await asyncMethod.call(instance, arg);
return instance;
}
That can be done, like this:
class test
{
constructor () { return Promise.resolve (this); }
}
Or with real delays added, any asynchronous event, or setTimeout for instance:
class test
{
constructor ()
{
return new Promise ( (resolve, reject) =>
{ //doing something really delayed
setTimeout (resolve, 5, this);
});
}
doHello(a) {console.log("hello: " + a);}
}
async function main()
{
new test().then(a=> a.doHello("then")); //invoking asynchronously
console.log("testing"); //"testing" will be printed 5 seconds before "hello"
(await new test()).doHello("await"); //invoking synchronously
}
main();
In some cases, when involving inheritance, can't be returned Promise from base class constructor, it will mess with this pointer. First idea is adding function then to make the class promise alike, but it is problematic. My workaround is using a private variable #p retaining the promise, and function _then (instead of then) which should act on completion of #p
class basetest
{
#p = null;
constructor (){this.#p = Promise.resolve(this);}
async _then (func)
{
return this.#p.then ( (ths) =>
{
this.#p = null;
if (func) func (ths);
return this;
});
}
doHello(a) {console.log("hello: " + a);}
}
class test extends basetest
{
constructor(context)
{
super(context);
this.msg = "test: ";
}
doTest(a) {console.log(this.msg + a);}
}
async function main()
{
(await new test()._then()).doHello("await");//synchronous call
//note, now we use _then instead of then
(new test())._then(a=>{a.doHello("then");a.doTest("then");} );//asynchronous call
}
main();
And suppose a some webgl, with async image loading, generating a mesh and drawing a vertex array object:
class HeightMap extends GlVAObject
{
#vertices = [];
constructor (src, crossOrigin = "")
{
//super(theContextSetup);
let image = new Image();
image.src = src;
image.crossOrigin = crossOrigin;
return new Promise ( (resolve, reject) =>
{
image.addEventListener('load', () =>
{
//reading pixel values from image into this.#vertices
//and generate a heights map
//...
resolve(this);
} );
});
}
///...
}
function drawVao(vao) {/*do something*/}
async function main()
{
let vao = await new HeightMap ("./heightmaps/ArisonaCraterHeightMap.png");
drawVao(vao);
///...
}
/*
//version of main with asynchronous call
async function main()
{
new HeightMap ("./heightmaps/ArisonaCraterHeightMap.png").then (vao => drawVao(vao));
///...
}
*/
main();
Second variant with _then, as it really works in real life:
class HeightMap extends GlVAObject
{
#vertices = [];
constructor (src, crossOrigin = "")
{
//super(theContextSetup);
let image = new Image();
image.src = src;
image.crossOrigin = crossOrigin;
this.#p = Promise ( (resolve, reject) =>
{
image.addEventListener('load', () =>
{
//...
resolve(this);
} );
});
}
async _then (func)
{
return this.#p.then ( (ths) =>
{
this.#p = null;
if (func) func (ths);
return this;
});
}
///...
}
function drawVao(vao) {/*do something*/}
async function main()
{
new HeightMap ("./heightmaps/ArisonaCraterHeightMap.png")._then(vao => drawVao(vao) );
///...
}
/*
//version of main with synchronous call
async function main()
{
vao = (await new HeightMap ("./heightmaps/ArisonaCraterHeightMap.png"))._then();
drawVao(vao);
///...
}*/
main();
You may immediately invoke an anonymous async function that returns message and set it to the message variable. You might want to take a look at immediately invoked function expressions (IEFES), in case you are unfamiliar with this pattern. This will work like a charm.
var message = (async function() { return await grabUID(uid) })()
You should add then function to instance. Promise will recognize it as a thenable object with Promise.resolve automatically
const asyncSymbol = Symbol();
class MyClass {
constructor() {
this.asyncData = null
}
then(resolve, reject) {
return (this[asyncSymbol] = this[asyncSymbol] || new Promise((innerResolve, innerReject) => {
this.asyncData = { a: 1 }
setTimeout(() => innerResolve(this.asyncData), 3000)
})).then(resolve, reject)
}
}
async function wait() {
const asyncData = await new MyClass();
alert('run 3s later')
alert(asyncData.a)
}
#slebetmen's accepted answer explains well why this doesn't work. In addition to the two patterns presented in that answer, another option is to only access your async properties through a custom async getter. The constructor() can then trigger the async creation of the properties, but the getter then checks to see if the property is available before it uses or returns it.
This approach is particularly useful when you want to initialize a global object once on startup, and you want to do it inside a module. Instead of initializing in your index.js and passing the instance in the places that need it, simply require your module wherever the global object is needed.
Usage
const instance = new MyClass();
const prop = await instance.getMyProperty();
Implementation
class MyClass {
constructor() {
this.myProperty = null;
this.myPropertyPromise = this.downloadAsyncStuff();
}
async downloadAsyncStuff() {
// await yourAsyncCall();
this.myProperty = 'async property'; // this would instead by your async call
return this.myProperty;
}
getMyProperty() {
if (this.myProperty) {
return this.myProperty;
} else {
return this.myPropertyPromise;
}
}
}
The closest you can get to an asynchronous constructor is by waiting for it to finish executing if it hasn't already in all of its methods:
class SomeClass {
constructor() {
this.asyncConstructor = (async () => {
// Perform asynchronous operations here
})()
}
async someMethod() {
await this.asyncConstructor
// Perform normal logic here
}
}
The other answers are missing the obvious. Simply call an async function from your constructor:
constructor() {
setContentAsync();
}
async setContentAsync() {
let uid = this.getAttribute('data-uid')
let message = await grabUID(uid)
const shadowRoot = this.attachShadow({mode: 'open'})
shadowRoot.innerHTML = `
<div id="email">A random email message has appeared. ${message}</div>
`
}

typescript class with constructor calling an internal async function that initiliaze a property [duplicate]

At the moment, I'm attempting to use async/await within a class constructor function. This is so that I can get a custom e-mail tag for an Electron project I'm working on.
customElements.define('e-mail', class extends HTMLElement {
async constructor() {
super()
let uid = this.getAttribute('data-uid')
let message = await grabUID(uid)
const shadowRoot = this.attachShadow({mode: 'open'})
shadowRoot.innerHTML = `
<div id="email">A random email message has appeared. ${message}</div>
`
}
})
At the moment however, the project does not work, with the following error:
Class constructor may not be an async method
Is there a way to circumvent this so that I can use async/await within this? Instead of requiring callbacks or .then()?
This can never work.
The async keyword allows await to be used in a function marked as async but it also converts that function into a promise generator. So a function marked with async will return a promise. A constructor on the other hand returns the object it is constructing. Thus we have a situation where you want to both return an object and a promise: an impossible situation.
You can only use async/await where you can use promises because they are essentially syntax sugar for promises. You can't use promises in a constructor because a constructor must return the object to be constructed, not a promise.
There are two design patterns to overcome this, both invented before promises were around.
Use of an init() function. This works a bit like jQuery's .ready(). The object you create can only be used inside its own init or ready function:
Usage:
var myObj = new myClass();
myObj.init(function() {
// inside here you can use myObj
});
Implementation:
class myClass {
constructor () {
}
init (callback) {
// do something async and call the callback:
callback.bind(this)();
}
}
Use a builder. I've not seen this used much in javascript but this is one of the more common work-arounds in Java when an object needs to be constructed asynchronously. Of course, the builder pattern is used when constructing an object that requires a lot of complicated parameters. Which is exactly the use-case for asynchronous builders. The difference is that an async builder does not return an object but a promise of that object:
Usage:
myClass.build().then(function(myObj) {
// myObj is returned by the promise,
// not by the constructor
// or builder
});
// with async/await:
async function foo () {
var myObj = await myClass.build();
}
Implementation:
class myClass {
constructor (async_param) {
if (typeof async_param === 'undefined') {
throw new Error('Cannot be called directly');
}
}
static build () {
return doSomeAsyncStuff()
.then(function(async_result){
return new myClass(async_result);
});
}
}
Implementation with async/await:
class myClass {
constructor (async_param) {
if (typeof async_param === 'undefined') {
throw new Error('Cannot be called directly');
}
}
static async build () {
var async_result = await doSomeAsyncStuff();
return new myClass(async_result);
}
}
Note: although in the examples above we use promises for the async builder they are not strictly speaking necessary. You can just as easily write a builder that accept a callback.
Note on calling functions inside static functions.
This has nothing whatsoever to do with async constructors but with what the keyword this actually mean (which may be a bit surprising to people coming from languages that do auto-resolution of method names, that is, languages that don't need the this keyword).
The this keyword refers to the instantiated object. Not the class. Therefore you cannot normally use this inside static functions since the static function is not bound to any object but is bound directly to the class.
That is to say, in the following code:
class A {
static foo () {}
}
You cannot do:
var a = new A();
a.foo() // NOPE!!
instead you need to call it as:
A.foo();
Therefore, the following code would result in an error:
class A {
static foo () {
this.bar(); // you are calling this as static
// so bar is undefinned
}
bar () {}
}
To fix it you can make bar either a regular function or a static method:
function bar1 () {}
class A {
static foo () {
bar1(); // this is OK
A.bar2(); // this is OK
}
static bar2 () {}
}
You can definitely do this, by returning an Immediately Invoked Async Function Expression from the constructor. IIAFE is the fancy name for a very common pattern that was required in order to use await outside of an async function, before top-level await became available:
(async () => {
await someFunction();
})();
We'll be using this pattern to immediately execute the async function in the constructor, and return its result as this:
// Sample async function to be used in the async constructor
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
class AsyncConstructor {
constructor(value) {
return (async () => {
// Call async functions here
await sleep(500);
this.value = value;
// Constructors return `this` implicitly, but this is an IIFE, so
// return `this` explicitly (else we'd return an empty object).
return this;
})();
}
}
(async () => {
console.log('Constructing...');
const obj = await new AsyncConstructor(123);
console.log('Done:', obj);
})();
To instantiate the class, use:
const instance = await new AsyncConstructor(...);
For TypeScript, you need to assert that the type of the constructor is the class type, rather than a promise returning the class type:
class AsyncConstructor {
constructor(value) {
return (async (): Promise<AsyncConstructor> => {
// ...
return this;
})() as unknown as AsyncConstructor; // <-- type assertion
}
}
Downsides
Extending a class with an async constructor will have a limitation. If you need to call super in the constructor of the derived class, you'll have to call it without await. If you need to call the super constructor with await, you'll run into TypeScript error 2337: Super calls are not permitted outside constructors or in nested functions inside constructors.
It's been argued that it's a "bad practice" to have a constructor function return a Promise.
Before using this solution, determine whether you'll need to extend the class, and document that the constructor must be called with await.
Because async functions are promises, you can create a static function on your class which executes an async function which returns the instance of the class:
class Yql {
constructor () {
// Set up your class
}
static init () {
return (async function () {
let yql = new Yql()
// Do async stuff
await yql.build()
// Return instance
return yql
}())
}
async build () {
// Do stuff with await if needed
}
}
async function yql () {
// Do this instead of "new Yql()"
let yql = await Yql.init()
// Do stuff with yql instance
}
yql()
Call with let yql = await Yql.init() from an async function.
Unlike others have said, you can get it to work.
JavaScript classes can return literally anything from their constructor, even an instance of another class. So, you might return a Promise from the constructor of your class that resolves to its actual instance.
Below is an example:
export class Foo {
constructor() {
return (async () => {
// await anything you want
return this; // Return the newly-created instance
})();
}
}
Then, you'll create instances of Foo this way:
const foo = await new Foo();
The stopgap solution
You can create an async init() {... return this;} method, then instead do new MyClass().init() whenever you'd normally just say new MyClass().
This is not clean because it relies on everyone who uses your code, and yourself, to always instantiate the object like so. However if you're only using this object in a particular place or two in your code, it could maybe be fine.
A significant problem though occurs because ES has no type system, so if you forget to call it, you've just returned undefined because the constructor returns nothing. Oops. Much better would be to do something like:
The best thing to do would be:
class AsyncOnlyObject {
constructor() {
}
async init() {
this.someField = await this.calculateStuff();
}
async calculateStuff() {
return 5;
}
}
async function newAsync_AsyncOnlyObject() {
return await new AsyncOnlyObject().init();
}
newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}
The factory method solution (slightly better)
However then you might accidentally do new AsyncOnlyObject, you should probably just create factory function that uses Object.create(AsyncOnlyObject.prototype) directly:
async function newAsync_AsyncOnlyObject() {
return await Object.create(AsyncOnlyObject.prototype).init();
}
newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}
However say you want to use this pattern on many objects... you could abstract this as a decorator or something you (verbosely, ugh) call after defining like postProcess_makeAsyncInit(AsyncOnlyObject), but here I'm going to use extends because it sort of fits into subclass semantics (subclasses are parent class + extra, in that they should obey the design contract of the parent class, and may do additional things; an async subclass would be strange if the parent wasn't also async, because it could not be initialized the same way):
Abstracted solution (extends/subclass version)
class AsyncObject {
constructor() {
throw new Error('classes descended from AsyncObject must be initialized as (await) TheClassName.anew(), rather than new TheClassName()');
}
static async anew(...args) {
var R = Object.create(this.prototype);
R.init(...args);
return R;
}
}
class MyObject extends AsyncObject {
async init(x, y=5) {
this.x = x;
this.y = y;
// bonus: we need not return 'this'
}
}
MyObject.anew('x').then(console.log);
// output: MyObject {x: "x", y: 5}
(do not use in production: I have not thought through complicated scenarios such as whether this is the proper way to write a wrapper for keyword arguments.)
Based on your comments, you should probably do what every other HTMLElement with asset loading does: make the constructor start a sideloading action, generating a load or error event depending on the result.
Yes, that means using promises, but it also means "doing things the same way as every other HTML element", so you're in good company. For instance:
var img = new Image();
img.onload = function(evt) { ... }
img.addEventListener("load", evt => ... );
img.onerror = function(evt) { ... }
img.addEventListener("error", evt => ... );
img.src = "some url";
this kicks off an asynchronous load of the source asset that, when it succeeds, ends in onload and when it goes wrong, ends in onerror. So, make your own class do this too:
class EMailElement extends HTMLElement {
connectedCallback() {
this.uid = this.getAttribute('data-uid');
}
setAttribute(name, value) {
super.setAttribute(name, value);
if (name === 'data-uid') {
this.uid = value;
}
}
set uid(input) {
if (!input) return;
const uid = parseInt(input);
// don't fight the river, go with the flow, use a promise:
new Promise((resolve, reject) => {
yourDataBase.getByUID(uid, (err, result) => {
if (err) return reject(err);
resolve(result);
});
})
.then(result => {
this.renderLoaded(result.message);
})
.catch(error => {
this.renderError(error);
});
}
};
customElements.define('e-mail', EmailElement);
And then you make the renderLoaded/renderError functions deal with the event calls and shadow dom:
renderLoaded(message) {
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.innerHTML = `
<div class="email">A random email message has appeared. ${message}</div>
`;
// is there an ancient event listener?
if (this.onload) {
this.onload(...);
}
// there might be modern event listeners. dispatch an event.
this.dispatchEvent(new Event('load'));
}
renderFailed() {
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.innerHTML = `
<div class="email">No email messages.</div>
`;
// is there an ancient event listener?
if (this.onload) {
this.onerror(...);
}
// there might be modern event listeners. dispatch an event.
this.dispatchEvent(new Event('error'));
}
Also note I changed your id to a class, because unless you write some weird code to only ever allow a single instance of your <e-mail> element on a page, you can't use a unique identifier and then assign it to a bunch of elements.
I usually prefer a static async method that returns a new instance, but here's another way to do it. It's closer to literally awaiting a constructor. It works with TypeScript.
class Foo {
#promiseReady;
constructor() {
this.#promiseReady = this.#init();
}
async #init() {
await someAsyncStuff();
return this;
}
ready() {
return this.promiseReady;
}
}
let foo = await new Foo().ready();
I made this test-case based on #Downgoat's answer.
It runs on NodeJS.
This is Downgoat's code where the async part is provided by a setTimeout() call.
'use strict';
const util = require( 'util' );
class AsyncConstructor{
constructor( lapse ){
this.qqq = 'QQQ';
this.lapse = lapse;
return ( async ( lapse ) => {
await this.delay( lapse );
return this;
})( lapse );
}
async delay(ms) {
return await new Promise(resolve => setTimeout(resolve, ms));
}
}
let run = async ( millis ) => {
// Instatiate with await, inside an async function
let asyncConstructed = await new AsyncConstructor( millis );
console.log( 'AsyncConstructor: ' + util.inspect( asyncConstructed ));
};
run( 777 );
My use case is DAOs for the server-side of a web application.
As I see DAOs, they are each one associated to a record format, in my case a MongoDB collection like for instance a cook.
A cooksDAO instance holds a cook's data.
In my restless mind I would be able to instantiate a cook's DAO providing the cookId as an argument, and the instantiation would create the object and populate it with the cook's data.
Thus the need to run async stuff into the constructor.
I wanted to write:
let cook = new cooksDAO( '12345' );
to have available properties like cook.getDisplayName().
With this solution I have to do:
let cook = await new cooksDAO( '12345' );
which is very similar to the ideal.
Also, I need to do this inside an async function.
My B-plan was to leave the data loading out of the constructor, based on #slebetman suggestion to use an init function, and do something like this:
let cook = new cooksDAO( '12345' );
async cook.getData();
which doesn't break the rules.
Use the async method in constructor???
constructor(props) {
super(props);
(async () => await this.qwe(() => console.log(props), () => console.log(props)))();
}
async qwe(q, w) {
return new Promise((rs, rj) => {
rs(q());
rj(w());
});
}
If you can avoid extend, you can avoid classes all together and use function composition as constructors. You can use the variables in the scope instead of class members:
async function buildA(...) {
const data = await fetch(...);
return {
getData: function() {
return data;
}
}
}
and simple use it as
const a = await buildA(...);
If you're using typescript or flow, you can even enforce the interface of the constructors
Interface A {
getData: object;
}
async function buildA0(...): Promise<A> { ... }
async function buildA1(...): Promise<A> { ... }
...
I found myself in a situation like this and ended up using an IIFE
// using TypeScript
class SomeClass {
constructor() {
// do something here
}
doSomethingAsync(): SomeClass {
(async () => await asyncTask())();
return this;
}
}
const someClass = new SomeClass().doSomethingAsync();
If you have other tasks that are dependant on the async task you can run them after the IIFE completes its execution.
A lot of great knowledge here and some super() thoughtful responses. In short the technique outlined below is fairly straightforward, non-recursive, async-compatible and plays by the rules. More importantly I don't believe it has been properly covered here yet - though please correct me if wrong!
Instead of method calls we simply assign an II(A)FE to an instance prop:
// it's async-lite!
class AsyncLiteComponent {
constructor() {
// our instance includes a 'ready' property: an IIAFE promise
// that auto-runs our async needs and then resolves to the instance
// ...
// this is the primary difference to other answers, in that we defer
// from a property, not a method, and the async functionality both
// auto-runs and the promise/prop resolves to the instance
this.ready = (async () => {
// in this example we're auto-fetching something
this.msg = await AsyncLiteComponent.msg;
// we return our instance to allow nifty one-liners (see below)
return this;
})();
}
// we keep our async functionality in a static async getter
// ... technically (with some minor tweaks), we could prefetch
// or cache this response (but that isn't really our goal here)
static get msg() {
// yes I know - this example returns almost immediately (imagination people!)
return fetch('data:,Hello%20World%21').then((e) => e.text());
}
}
Seems simple enough, how is it used?
// Ok, so you *could* instantiate it the normal, excessively boring way
const iwillnotwait = new AsyncLiteComponent();
// and defer your waiting for later
await iwillnotwait.ready
console.log(iwillnotwait.msg)
// OR OR OR you can get all async/awaity about it!
const onlywhenimready = await new AsyncLiteComponent().ready;
console.log(onlywhenimready.msg)
// ... if you're really antsy you could even "pre-wait" using the static method,
// but you'd probably want some caching / update logic in the class first
const prefetched = await AsyncLiteComponent.msg;
// ... and I haven't fully tested this but it should also be open for extension
class Extensior extends AsyncLiteComponent {
constructor() {
super();
this.ready.then(() => console.log(this.msg))
}
}
const extendedwaittime = await new Extensior().ready;
Before posting I had a brief discussion on the viability of this technique in the comments of #slebetman's comprehensive answer. I wasn't entirely convinced by the outright dismissal, so thought I would open it up to further debate / tear down. Please do your worst :)
You can use Proxy's construct handle to do this, the code like this:
const SomeClass = new Proxy(class A {
constructor(user) {
this.user = user;
}
}, {
async construct(target, args, newTarget) {
const [name] = args;
// you can use await in here
const user = await fetch(name);
// invoke new A here
return new target(user);
}
});
const a = await new SomeClass('cage');
console.log(a.user); // user info
Variation on the builder pattern, using call():
function asyncMethod(arg) {
function innerPromise() { return new Promise((...)=> {...}) }
innerPromise().then(result => {
this.setStuff(result);
}
}
const getInstance = async (arg) => {
let instance = new Instance();
await asyncMethod.call(instance, arg);
return instance;
}
That can be done, like this:
class test
{
constructor () { return Promise.resolve (this); }
}
Or with real delays added, any asynchronous event, or setTimeout for instance:
class test
{
constructor ()
{
return new Promise ( (resolve, reject) =>
{ //doing something really delayed
setTimeout (resolve, 5, this);
});
}
doHello(a) {console.log("hello: " + a);}
}
async function main()
{
new test().then(a=> a.doHello("then")); //invoking asynchronously
console.log("testing"); //"testing" will be printed 5 seconds before "hello"
(await new test()).doHello("await"); //invoking synchronously
}
main();
In some cases, when involving inheritance, can't be returned Promise from base class constructor, it will mess with this pointer. First idea is adding function then to make the class promise alike, but it is problematic. My workaround is using a private variable #p retaining the promise, and function _then (instead of then) which should act on completion of #p
class basetest
{
#p = null;
constructor (){this.#p = Promise.resolve(this);}
async _then (func)
{
return this.#p.then ( (ths) =>
{
this.#p = null;
if (func) func (ths);
return this;
});
}
doHello(a) {console.log("hello: " + a);}
}
class test extends basetest
{
constructor(context)
{
super(context);
this.msg = "test: ";
}
doTest(a) {console.log(this.msg + a);}
}
async function main()
{
(await new test()._then()).doHello("await");//synchronous call
//note, now we use _then instead of then
(new test())._then(a=>{a.doHello("then");a.doTest("then");} );//asynchronous call
}
main();
And suppose a some webgl, with async image loading, generating a mesh and drawing a vertex array object:
class HeightMap extends GlVAObject
{
#vertices = [];
constructor (src, crossOrigin = "")
{
//super(theContextSetup);
let image = new Image();
image.src = src;
image.crossOrigin = crossOrigin;
return new Promise ( (resolve, reject) =>
{
image.addEventListener('load', () =>
{
//reading pixel values from image into this.#vertices
//and generate a heights map
//...
resolve(this);
} );
});
}
///...
}
function drawVao(vao) {/*do something*/}
async function main()
{
let vao = await new HeightMap ("./heightmaps/ArisonaCraterHeightMap.png");
drawVao(vao);
///...
}
/*
//version of main with asynchronous call
async function main()
{
new HeightMap ("./heightmaps/ArisonaCraterHeightMap.png").then (vao => drawVao(vao));
///...
}
*/
main();
Second variant with _then, as it really works in real life:
class HeightMap extends GlVAObject
{
#vertices = [];
constructor (src, crossOrigin = "")
{
//super(theContextSetup);
let image = new Image();
image.src = src;
image.crossOrigin = crossOrigin;
this.#p = Promise ( (resolve, reject) =>
{
image.addEventListener('load', () =>
{
//...
resolve(this);
} );
});
}
async _then (func)
{
return this.#p.then ( (ths) =>
{
this.#p = null;
if (func) func (ths);
return this;
});
}
///...
}
function drawVao(vao) {/*do something*/}
async function main()
{
new HeightMap ("./heightmaps/ArisonaCraterHeightMap.png")._then(vao => drawVao(vao) );
///...
}
/*
//version of main with synchronous call
async function main()
{
vao = (await new HeightMap ("./heightmaps/ArisonaCraterHeightMap.png"))._then();
drawVao(vao);
///...
}*/
main();
You may immediately invoke an anonymous async function that returns message and set it to the message variable. You might want to take a look at immediately invoked function expressions (IEFES), in case you are unfamiliar with this pattern. This will work like a charm.
var message = (async function() { return await grabUID(uid) })()
You should add then function to instance. Promise will recognize it as a thenable object with Promise.resolve automatically
const asyncSymbol = Symbol();
class MyClass {
constructor() {
this.asyncData = null
}
then(resolve, reject) {
return (this[asyncSymbol] = this[asyncSymbol] || new Promise((innerResolve, innerReject) => {
this.asyncData = { a: 1 }
setTimeout(() => innerResolve(this.asyncData), 3000)
})).then(resolve, reject)
}
}
async function wait() {
const asyncData = await new MyClass();
alert('run 3s later')
alert(asyncData.a)
}
#slebetmen's accepted answer explains well why this doesn't work. In addition to the two patterns presented in that answer, another option is to only access your async properties through a custom async getter. The constructor() can then trigger the async creation of the properties, but the getter then checks to see if the property is available before it uses or returns it.
This approach is particularly useful when you want to initialize a global object once on startup, and you want to do it inside a module. Instead of initializing in your index.js and passing the instance in the places that need it, simply require your module wherever the global object is needed.
Usage
const instance = new MyClass();
const prop = await instance.getMyProperty();
Implementation
class MyClass {
constructor() {
this.myProperty = null;
this.myPropertyPromise = this.downloadAsyncStuff();
}
async downloadAsyncStuff() {
// await yourAsyncCall();
this.myProperty = 'async property'; // this would instead by your async call
return this.myProperty;
}
getMyProperty() {
if (this.myProperty) {
return this.myProperty;
} else {
return this.myPropertyPromise;
}
}
}
The closest you can get to an asynchronous constructor is by waiting for it to finish executing if it hasn't already in all of its methods:
class SomeClass {
constructor() {
this.asyncConstructor = (async () => {
// Perform asynchronous operations here
})()
}
async someMethod() {
await this.asyncConstructor
// Perform normal logic here
}
}
The other answers are missing the obvious. Simply call an async function from your constructor:
constructor() {
setContentAsync();
}
async setContentAsync() {
let uid = this.getAttribute('data-uid')
let message = await grabUID(uid)
const shadowRoot = this.attachShadow({mode: 'open'})
shadowRoot.innerHTML = `
<div id="email">A random email message has appeared. ${message}</div>
`
}

Prototype chaining using JavaScript object oriented

I need to do something like this:
send('message').user('usr1').message('msg').to('usr2');
So send function accept one argument and has a prototype called user and user accept one argument and has a prototype called message and so on.
I just wrote this
function send(type){
console.log(type);
}
send.prototype.user = function (usr) {
console.log(usr);
}
But how can i go deeply and chaining like in the provided example?
You can use class and flow pattern
class Sender {
constructor(msg) {
this.msg = [msg];
}
user(usr) {
this.usr = usr;
return this;
}
message(msg) {
this.msg.push(msg);
return this;
}
to(usr) {
this.to = usr;
console.log(this);
return this;
}
}
function send(msg) {
return new Sender(msg);
}
send('message').user('usr1').message('msg').to('usr2');
You need your functions to return the specific type like this:
function send(type){
return new User(type); // Return some user
}
function user (usr) {
return new Message(usr); // Return some message
}
You seem to be conflating the prototype chain with function chaining. The former is how javascript does inheritance. The latter is what you seem to want to do: call a function, then call a function on its return value, then call a function on its return value, etc.
In may cases, function chaining involves functions returning a reference to the object on which they reside. For example:
const sampleObject = {
sayHello: function() {
console.log('hello');
return this; // <-- necessary to allow function chaining
},
sayGoodBye: function() {
console.log('good bye');
return this;
}
}
sampleObject.sayHello().sayGoodBye();
If you want to have the functions return objects other than this that's possible too, but exactly what to return will depend on what you're trying to do.
Since "Object Oriented" is in your title, I thought I'd take the chance to give an example of an OO way to analyse this.
First of all we'll want to identify the object instigating the actions. "Send" is not an object, it is the name of an action, so that's not going to be our object. There are two candidates left in your code: user and message.
There are two ways to look at this.
Messages take care of themselves.
Users do all the actions.
The pros of 1.
localises the functionality of dealing with messages to a specific class
The cons of 1.
Semantically weird. Messages are generally passive.
Pros of 2.
Semantically makes sense. People act on messages, not the other way around.
Cons of 2.
If users are responsible for everything they do, the class will become bloated and difficult to maintain.
So, we have a conflict between avoiding bad semantics or avoiding bloating a class.
Perhaps there is a third way. What if we had an object that makes sure messages get where they're meant to go?
In the real world that's the post office.
This essentially gives us a factory pattern type class.
function PostOffice()
{
}
PostOffice.prototype.createMessage = function(messageBody)
{
this.message =
{
"body":messageBody,
"fromUser": null,
"toUser": null
};
return this;
};
PostOffice.prototype.from = function(user)
{
this.message.fromUser = user;
return this;
};
PostOffice.prototype.to = function(user)
{
this.message.toUser = user;
return this;
};
PostOffice.prototype.send = function()
{
//whatever sending means
};
var po = new PostOffice();
po.createMessage('hi').from('user1').to('user2').send();
This is obviously a toy example, but hopefully you get the idea.

TypeScript call function in dynamic (anonymous) function

I am trying to create a dynamic function in TypeScript which calls an already existing function like:
let dynamicFunction = new Function("existingFunction(\"asdf\");");
function existingFunction(name: string) {
console.log(name);
}
While debugging in chrome dynamicFunction looks like this:
(function() {
existingFunction("asdf");
})
When I try to execute dynamicFunction, it says "Uncaught ReferenceError: existingFunction is not defined", which is no surprise because it's a different scope, but how can I actually call exisitingFunction inside dynamicFunction?
Any help would be greatly appreciated!
Edit:
to be more precise: I've got a typescript file which contains one module.
This module exports a function which should return the created dynamic function.
The created dynamicFunction is then used in another module which actually contains the exisitingFunction.
I've chosen this approach because I need to convert a given string to an executable condition, which will be executed many times.
For example: convert string "VALUE==1" to:
function () {
return exisitingFunction("VALUE") == 1;
}
A short example of how it should look like:
parser.ts:
export module Parser {
export function getFunction(expression: string) {
// Calculating condition...
let condition = "existingFunction(\"VALUE\") == 1;"
return new Function(condition);
}
}
condition.ts:
import { Parser } from "./parser";
class Condition {
// getting the DynamicFunction
private _dynamicFunction = Parser.getFunction("VALUE==1");
someFunctionInsideCondition() {
// Calling the DynamicFunction
this._dynamicFunction();
}
}
// Maybe this function should be somewhere else?
function existingFunction(name: string) {
console.log(name);
return 1;
}
I hope this explains my problem a little bit better.
From the Function documentation
Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using eval with code for a function expression.
so you'll have to pass existingFunction as an argument or define it in the global space.
try with
var existingFunction = function(name: string) {
console.log(name);
}
Also have a look at eval which will give you access to the current scope ...
--- Update
After the question update and considering your comment about not wanting to use eval because of security concerns (with which i totally agree)
The problem is that in the generated function's scope, this is undefined. Making your existingFunction part of the global scope is already a bad idea and between Typescript and the modules architecture doesn't seem possible at all.
So why not passing a context to the generated function?
This will allow you to control how much of your application to expose to the generated function, while giving it access to external methods.
Something along the lines of:
class Parser {
static getFunction(expression) {
let condition = new Function("context", "context.existingFunction(\"VALUE\") == 1;");
return condition;
}
}
class Condition {
constructor() {
this._dynamicFunction = Parser.getFunction("VALUE==1");
}
someFunctionInsideCondition() {
// Calling the DynamicFunction
this._dynamicFunction(this);
}
existingFunction(name) {
console.log("hello " + name);
return 1;
};
}
let c = new Condition();
c.someFunctionInsideCondition();
Of course your context can be a different object instead of this, where you keep all your utility functions.
I had to donwpile (compile it down, my own word) to es2015 to make the example run here, but I made it originally in Typescript and works fine
I would skip the usage of new Function and instead do it as follows.
The parser.ts file would contain this:
export class FunctionGenerator {
constructor(private fn: Function) {}
makeFunction(args: string): Function {
const [variable, val] = args.split("==");
return () => this.fn(variable) == val;
}
}
This is basically a factory that allows creating a series of functions that call the function passed when the factory is created. You can then use makeFunction for the specific checks you want to perform. (Note that I used == like in your question. I much prefer using === unless there's a reason against it.)
It can then be used like this:
import * as parser from "./parser";
let vars = {};
// This is a simulation of your funciton. It just plucks values from `vars`.
function existingFunction(name: string) {
return vars[name];
}
function resetVars() {
vars = {
"VALUE": 1,
"FOO": 2,
"BAR": 3,
};
}
function test(gen) {
const fn1 = gen.makeFunction("VALUE==1");
console.log(fn1(), "should be true");
const fn2 = gen.makeFunction("BAR==3");
console.log(fn2(), "should be true");
vars["BAR"] = 7;
// Call the same function again, but with a new value in `vars`.
console.log(fn2(), "should be false");
const fn3 = gen.makeFunction("BAR==1000");
console.log(fn3(), "should be false");
}
resetVars();
const gen = new parser.FunctionGenerator(existingFunction);
test(gen);

How can I preserve lexical scope in TypeScript with a callback function

I have a TypeScript class, with a function that I intend to use as a callback:
removeRow(_this:MyClass): void {
...
// 'this' is now the window object
// I must use '_this' to get the class itself
...
}
I pass it in to another function
this.deleteRow(this.removeRow);
which in turn calls a jQuery Ajax method, which if successful, invokes the callback like this:
deleteItem(removeRowCallback: (_this:MyClass) => void ): void {
$.ajax(action, {
data: { "id": id },
type: "POST"
})
.done(() => {
removeRowCallback(this);
})
.fail(() => {
alert("There was an error!");
});
}
The only way I can preserve the 'this' reference to my class is to pass it on to the callback, as demonstrated above. It works, but it's pants code. If I don't wire up the 'this' like this (sorry), then any reference to this in the callback method has reverted to the Window object. Because I'm using arrow functions all the way, I expected that the 'this' would be the class itself, as it is elsewhere in my class.
Anyone know how to pass callbacks around in TypeScript, preserving lexical scope?
Edit 2014-01-28:
New readers, make sure you check out Zac's answer below.
He has a much neater solution that will let you define and instantiate a scoped function in the class definition using the fat arrow syntax.
The only thing I will add is that, in regard to option 5 in Zac's answer, it's possible to specify the method signature and return type without any repetition using this syntax:
public myMethod = (prop1: number): string => {
return 'asdf';
}
Edit 2013-05-28:
The syntax for defining a function property type has changed (since TypeScript version 0.8).
Previously you would define a function type like this:
class Test {
removeRow: (): void;
}
This has now changed to:
class Test {
removeRow: () => void;
}
I have updated my answer below to include this new change.
As a further aside: If you need to define multiple function signatures for the same function name (e.g. runtime function overloading) then you can use the object map notation (this is used extensively in the jQuery descriptor file):
class Test {
removeRow: {
(): void;
(param: string): string;
};
}
You need to define the signature for removeRow() as a property on your class but assign the implementation in the constructor.
There are a few different ways you can do this.
Option 1
class Test {
// Define the method signature here.
removeRow: () => void;
constructor (){
// Implement the method using the fat arrow syntax.
this.removeRow = () => {
// Perform your logic to remove the row.
// Reference `this` as needed.
}
}
}
If you want to keep your constructor minimal then you can just keep the removeRow method in the class definition and just assign a proxy function in the constructor:
Option 2
class Test {
// Again, define the method signature here.
removeRowProxy: () => void;
constructor (){
// Assign the method implementation here.
this.removeRowProxy = () => {
this.removeRow.apply(this, arguments);
}
}
removeRow(): void {
// ... removeRow logic here.
}
}
Option 3
And finally, if you're using a library like underscore or jQuery then you can just use their utility method to create the proxy:
class Test {
// Define the method signature here.
removeRowProxy: () => void;
constructor (){
// Use jQuery to bind removeRow to this instance.
this.removeRowProxy = $.proxy(this.removeRow, this);
}
removeRow(): void {
// ... removeRow logic here.
}
}
Then you can tidy up your deleteItem method a bit:
// Specify `Function` as the callback type.
// NOTE: You can define a specific signature if needed.
deleteItem(removeRowCallback: Function ): void {
$.ajax(action, {
data: { "id": id },
type: "POST"
})
// Pass the callback here.
//
// You don't need the fat arrow syntax here
// because the callback has already been bound
// to the correct scope.
.done(removeRowCallback)
.fail(() => {
alert("There was an error!");
});
}
UPDATE: See Sly's updated answer. It incorporates an improved version of the options below.
ANOTHER UPDATE: Generics
Sometimes you want to specify a generic type in a function signature without having to specify it on the the whole class. It took me a few tries to figure out the syntax, so I thought it might be worth sharing:
class MyClass { //no type parameter necessary here
public myGenericMethod = <T>(someArg:string): QPromise<T> => {
//implementation here...
}
}
Option 4
Here are a couple more syntaxes to add to Sly_cardinal's answer. These examples keep the function declaration and implementation in the same place:
class Test {
// Define the method signature AND IMPLEMENTATION here.
public removeRow: () => void = () => {
// Perform your logic to remove the row.
// Reference `this` as needed.
}
constructor (){
}
}
or
Option 5
A little more compact, but gives up explicit return type (the compiler should infer the return type anyway if not explicit):
class Test {
// Define implementation with implicit signature and correct lexical scope.
public removeRow = () => {
// Perform your logic to remove the row.
// Reference `this` as needed.
}
constructor (){
}
}
Use .bind() to preserve context within the callback.
Working code example:
window.addEventListener(
"resize",
(()=>{this.retrieveDimensionsFromElement();}).bind(this)
)
The code in original question would become something like this:
$.ajax(action, {
data: { "id": id },
type: "POST"
})
.done(
(() => {
removeRowCallback();
}).bind(this)
)
It will set the context (this) inside the callback function to whatever was passed as an argument to bind function, in this case the original this object.
This is sort of a cross post from another answer (Is there an alias for 'this' in TypeScript?). I re-applied the concept using the examples from above. I like it better than the options above because it explictly supports "this" scoping to both the class instance as well as the dynamic context entity that calls the method.
There are two versions below. I like the first one because the compiler assists in using it correctly (you won't as easily try to misuse the callback lambda itself as the callback, because of the explicitly typed parameter).
Test it out:
http://www.typescriptlang.org/Playground/
class Test {
private testString: string = "Fancy this!";
// Define the method signature here.
removeRowLambdaCallback(outerThis: Test): {(): void} {
alert("Defining callback for consumption");
return function(){
alert(outerThis.testString); // lexically scoped class instance
alert(this); // dynamically scoped context caller
// Put logic here for removing rows. Can refer to class
// instance as well as "this" passed by a library such as JQuery or D3.
}
}
// This approach looks nicer, but is more dangerous
// because someone might use this method itself, rather
// than the return value, as a callback.
anotherRemoveRowLambdaCallback(): {(): void} {
var outerThis = this;
alert("Defining another callback for consumption");
return function(){
alert(outerThis.testString); // lexically scoped class instance
alert(this); // dynamically scoped context caller
// Put logic here for removing rows. Can refer to class
// instance as well as "this" passed by a library such as JQuery or D3.
}
}
}
var t = new Test();
var callback1 = t.removeRowLambdaCallback(t);
var callback2 = t.anotherRemoveRowLambdaCallback();
callback1();
callback2();
Building upon sly and Zac's answers with types:
A complete hello world example. I hope this is welcome, seeing as this is the top result in Google, when searching for "typescript javascript callbacks"
type MyCallback = () => string;
class HelloWorld {
// The callback
public callback: MyCallback = () => {
return 'world';
}
// The caller
public caller(callback: MyCallback) {
alert('Hello ' + callback());
}
}
let hello = new HelloWorld();
hello.caller(hello.callback);
This gets transpiled into:
var HelloWorld = (function () {
function HelloWorld() {
// The callback
this.callback = function () {
return 'world';
};
}
// The caller
HelloWorld.prototype.caller = function (callback) {
alert('Hello ' + callback());
};
return HelloWorld;
}());
var hello = new HelloWorld();
hello.caller(hello.callback);
Hope someone finds it just a little useful. :)

Categories