0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

javascriptで let instance=await new myClass(); ってしたい

Posted at

適当な非同期処理(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

だいぶ雑だけど基本はこんな感じでいける。かなぁ...

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?