如何在不使用then方法的情况下定义promise链

JCa*_*los 7 javascript ecmascript-6 es6-promise

我已经找了类似的问题,但它们与JQuery或任何其他库有关.

首先,我写了这个:

const printIn1Sec = (value) => {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(value);
      resolve();
    }, 1000)
  });
};
Run Code Online (Sandbox Code Playgroud)

并以这种方式使用它:

printIn1Sec(1)
.then(() => printIn1Sec(2))
.then(() => printIn1Sec(3));
Run Code Online (Sandbox Code Playgroud)

我认为then非常重要,因为它允许我们在承诺得到解决后立即执行.

但我正在寻找这样的事情:

printIn1Sec(1)
.printIn1Sec(2)
.printIn1Sec(3);
Run Code Online (Sandbox Code Playgroud)

我注意到我需要一个可以访问此printIn1Sec方法的对象.所以我定义了一个类:

class Printer extends Promise {
  in1Sec(v) {
    return this.then(() => this.getPromise(v));
  }

  getPromise(value) {
    return new Printer(resolve => {
      setTimeout(() => {
        console.log(value);
        resolve();
      }, 1000)
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

并以这种方式使用它:

Printer.resolve().in1Sec(1).in1Sec(2).in1Sec(3);
Run Code Online (Sandbox Code Playgroud)

resolve从一开始就不得不承诺,以便开始连锁.但它仍然困扰着我.

您认为,有没有办法让它像以下一样工作?

printIn1Sec(1).printIn1Sec(2).printIn1Sec(3);
Run Code Online (Sandbox Code Playgroud)

我正在考虑一个新的类或方法,它可以接收这些值,存储它们,最后开始解析链.但它需要在最后调用aditional方法,以init为流程.

Fel*_*ing 7

如果你真的想在你的问题中创建一个可链接的界面,那么这样做:

const printIn1Sec = (function() {

  function setTimeoutPromise(timeout) {
    return new Promise(resolve => setTimeout(resolve, 1000));
  }

  function printIn1Sec(value, promise) {
    const newPromise = promise
      .then(() => setTimeoutPromise(1000))
      .then(() => console.log(value));

    return {
      printIn1Sec(value) {
        return printIn1Sec(value, newPromise);
      },
    };
  }

  return value => printIn1Sec(value, Promise.resolve());
}());

printIn1Sec(1)
  .printIn1Sec(2)
  .printIn1Sec(3);
Run Code Online (Sandbox Code Playgroud)

我们只是隐藏了内部函数中的所有承诺创建和链接.我将代码拆分为较小的函数,使其看起来更漂亮.


小智 6

您可以尝试asyncawait

const printIn1Sec = (value) => {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(value);
        resolve();
    }, 1000)
  });
};

async function fun(){
  await printIn1Sec(1);
  await printIn1Sec(2);
  await printIn1Sec(3);
}

fun();
Run Code Online (Sandbox Code Playgroud)