解题:使用 Promise 实现 machine 函数

题目.jpg
这道题是一位群友发出来的,就动手实现了一下。

思路:

  • machine(‘ygy’),可知 machine 函数需要传递一个参数,而后面的 execute() ,则执行打印,同时可知在执行 machine(‘ygy’) 函数之后会返回原型(machine.prototype);
  • 而第二个执行中添加了 do 函数,且在执行 do 函数之后可以继续执行 exxcute 函数,可知 do 函数会 return machine.prototype,同理,wait 和 waitFirst 函数也一样;
  • 一般这些链式调用,且会出现延迟时间调用的基本可以确认需要使用 Promise 来实现,而且显然有且只有一个 Promise 来进行实现,为了能实现给多个原型对象属性函数进行调用,因此会放在 machine 构造函数中进行存放;
  • 又因为 Promise.resolve().then(res => ‘…’).then()… 这个特点,在结合需要实现的链式调用,此时基本思路已经形成。

代码:

function machine(name) {
  this.name = name;
  this.myPromise = Promise.resolve(this.name);

  this.consoleName = () => {
    this.myPromise = this.myPromise.then((res) => {
      return `start ${res}`;
    });
  };
  this.consoleName();
  return arguments.callee.prototype;
}

// 动作
machine.prototype.do = function (action) {
  myPromise = myPromise.then((res) => {
    res && console.log(res);
    return `${name} ${action}`;
  });
  return machine.prototype;
};

// 延迟
machine.prototype.wait = function (num) {
  myPromise = myPromise.then(async (res) => {
    console.log(res);
    console.log(`wait ${num}s`);
    await new Promise((resolve) => {
      setTimeout(() => {
        resolve(null);
      }, num * 1000);
    });
  });
  return machine.prototype;
};

// 提前延迟
machine.prototype.waitFirst = function (num) {
  myPromise = myPromise.then(async (res) => {
    console.log(`waitFirst ${num}s`);
    await new Promise((resolve) => {
      setTimeout(() => {
        resolve(null);
      }, num * 1000);
    });
    return res;
  });
  return machine.prototype;
};

// 执行
machine.prototype.execute = async function () {
  myPromise.then((res) => {
    console.log(res);
  });
};

// machine("小卡车").execute();
// machine("小卡车").do("吃东西").execute();
// machine("小卡车").wait(3).do("吃东西").execute();
machine("小卡车").waitFirst(3).do("吃东西").execute();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值