我尝试一一内联调用类的方法,但第二个方法未定义。
如何在 ES6 类中实现此模式?
await new Mail().attachments(files).send()
邮件.js
export class Mail{
constructor(){
this.mail = {
*********
*********
};
}
attachments(files){
*********
*********
}
async send(){
try{
return await sendmail(this.mail, function(err) {
if(err){
return false
};
return true;
});
}catch(e){
throw e;
}
}
}
最佳答案
您需要确保附件
以return this
结尾,以便在其后面链接方法:
const sendmail = () => new Promise(res => setTimeout(res, 1000));
class Mail {
constructor() {
this.mail = 'mail';
}
attachments(files) {
console.log('adding attachments');
return this;
}
async send() {
console.log('sending...');
return sendmail(this.mail);
}
}
(async() => {
console.log('start');
const files = 'files';
await new Mail().attachments(files).send()
console.log('end');
})();
每当您想要定义要链接的方法时,请遵循相同的模式 - 在最后返回此
以返回实例化的对象。
关于javascript - 如何内联多次调用类方法(链式调用)JavaScript es6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51722196/