Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

javascript - es2016处理类构造函数中的回调[重复](es2016 handling callbacks in class constructor [duplicate])

I'm trying to write the following code into a es2015 class syntax:(我正在尝试将以下代码编写为es2015类语法:)

export function initialize(port) { return new Promise((resolve, reject) => { const application = express(); const server = application.listen(port, function listening(error) { if (error) reject(error); resolve(server); }); }); } const server = async initialize(port); es2015:(es2015:) class Server { constructor(port) { return new Promise((resolve, reject) => { const application = express(); const server = application.listen(port, function listening(error) { if (error) reject(error); resolve(server); }); }); } } const server = async new Server(port); // <-- not a good idea! Apparently returning and a Promise is not such a good idea when using the new which should return an instant instance.(显然,使用newPromise返回一个即时实例并不是一个好主意。) Any ideas?(有任何想法吗?)   ask by Karl Morrison translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use a separate initialise method and call that from instance:(您可以使用单独的initialise方法,并从实例调用该方法:)

class Server { constructor(port) { this.port = port; } initialise() { return new Promise((resolve, reject) => { const application = express(); const server = application.listen(this.port, function listening(error) { if (error) reject(error); resolve(server); }); }); } } const server = new Server(port); server.initialise().then(() => // do some stuff)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...