如何在javascript方法链中休眠方法 [英] How to sleep a method in javascript method chaining

查看:44
本文介绍了如何在javascript方法链中休眠方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使方法链中的方法进入睡眠(延迟)状态.为此,我将 setTimeout Promise 结合使用.这将要求 sleep 之后的任何方法都必须位于 then 之内.

I am trying to make a method sleep(delay) in method chaining. For this I am using setTimeout with Promise. This will require any method following the sleep to be inside the then.

现在我正在调用类似的函数

Right now I am calling the function like

lazyMan("John",console.log).eat("banana").sleep(5).then(d => {d.eat("apple");}); .

这是我的代码

function lazyMan(name, logFn) {
  logFn(name);
  return {
    eat: function(val) {
      console.log(val);
      return this;
    },
    sleep: function(timer) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log(`Sleeping for ${timer} seconds`);
          resolve(this);
        }, timer * 1000);
      }).then(d => this);
    }
  };
}
lazyMan("John", console.log)
  .eat("banana")
  .sleep(5)
  .then(d => {
    d.eat("apple");
  });

有没有一种方法可以修改我的函数以像 lazyMan("John",console.log).eat("banana").sleep(5).eat("apple")一样调用它.)并以相同顺序获取输出

Is there a way I can modify my function to call it like lazyMan("John", console.log).eat("banana").sleep(5).eat("apple") and get the output in same order

我已经通过在对象中添加sleep方法方法链(JS)

推荐答案

您可以保留对任务队列"的承诺,因此需要完成的所有操作都将通过添加到那里.).这提供了流畅的API来安排工作.

You can keep a promise for your "task queue", so anything that needs to be done, will be added onto there via .then(). This provides a fluent API for scheduling stuff.

function lazyMan(name, logFn) {
  logFn(name);
  let taskQueue = Promise.resolve();
  const addTask = f => {
    taskQueue = taskQueue.then(f);
  }
  return {
    eat: function(val) {
      addTask(() => console.log(`Eating [${val}]`));
      return this;
    },
    sleep: function(timer) {
      addTask(() => new Promise((resolve, reject) => {
        console.log(`Start sleeping for ${timer} seconds`);
        setTimeout(() => {
          console.log(`End sleeping for ${timer} seconds`);
          resolve();
        }, timer * 1000);
      }))
      return this;
    }
  };
}

lazyMan("John", console.log)
  .eat("banana")
  .sleep(5)
  .eat("apple");

请注意,此更改意味着每个操作在技术上都是异步的.但是,这至少是统一的,因此牢记这一点的可能性很小.

Note that this change means that every action is technically asynchronous. However, that's at least uniform, so it's less of a chance of a surprise when keeping it in mind.

这篇关于如何在javascript方法链中休眠方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆