適当な非同期処理(Promise)
async function waitNsecond(n){
return new Promise(function(resolve,reject){
setTimeout(resolve,1000);
});
}
type1
// set super class
var SUPER=Array;
// define async constructor
async function constructor(...args){
// console.log(this);
SUPER.call(this);
this.push(...args);
await waitNsecond(1);
}
// define async generate class
function myAsyncClass(...args){
if(new.target){
return new Promise(async function(resolve,reject){
let instance=Object.create(myAsyncClass.prototype);
await constructor.call(instance,...args);
resolve(instance);
});
}
}
// set prototype
myAsyncClass.prototype=Object.create(SUPER.prototype);
Object.defineProperty(myAsyncClass.prototype, 'constructor', { value: myAsyncClass, enumerable: false, writable: true });
// define method
myAsyncClass.prototype.printAll=function(){ console.log(this.join()); };
type2
class myAsyncClass extends Array {
constructor(...args){
super();
let instance=this;
return new Promise(async function(resolve,reject){
instance.push(...args);
await waitNsecond(1);
resolve(instance);
});
};
printAll(){
console.log(this.join());
};
}
結果
let instance=await new myAsyncClass(5,6,7,8,9);
instance.constructor===myAsyncClass;
instance.printAll(); // 5,6,7,8,9
だいぶ雑だけど基本はこんな感じでいける。かなぁ...