如何多次调用 class 内联方法(链调用)JavaScript es6

How to make multiple calls to class methods inline(chain calls)JavaScript es6

我尝试一个一个地内联调用 class 的方法,但第二个方法未定义。

如何在 ES6 中实现此模式 class?

await new Mail().attachments(files).send()

mail.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;
        }


    }
}

您需要确保 attachmentsreturn 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');
})();

每当您想定义要链接的方法时,请遵循相同的模式 - return this 在末尾以便 return 实例化对象。