简体   繁体   English

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

[英]How to define a promise chain without using then method

I already looked for similar questions, but they are related to JQuery or any other library. 我已经找了类似的问题,但它们与JQuery或任何其他库有关。

First, I wrote this: 首先,我写了这个:

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

And used it in this way: 并以这种方式使用它:

printIn1Sec(1)
.then(() => printIn1Sec(2))
.then(() => printIn1Sec(3));

I think then is very important, because it allows us to execute something as soon as the promise is resolved. 我认为then非常重要,因为它允许我们在承诺得到解决后立即执行。

But I was looking for something like this: 但我正在寻找这样的事情:

printIn1Sec(1)
.printIn1Sec(2)
.printIn1Sec(3);

I noticed I needed an object with access to this printIn1Sec method. 我注意到我需要一个可以访问此printIn1Sec方法的对象。 So I defined a class: 所以我定义了一个类:

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

  getPromise(value) {
    return new Printer(resolve => {
      setTimeout(() => {
        console.log(value);
        resolve();
      }, 1000)
    })
  }
}

And used it this way: 并以这种方式使用它:

Printer.resolve().in1Sec(1).in1Sec(2).in1Sec(3);

I had to resolve the Promise from the beginning, in order to the start the chain. 我必须从一开始就resolve Promise,以便开始链。 But it still bothers me. 但它仍然困扰着我。

Do you think, is there a way to get it working like the following? 您认为,有没有办法让它像以下一样工作?

printIn1Sec(1).printIn1Sec(2).printIn1Sec(3);

I was thinking in a new class or method, that could receive these values, store them, and finally start resolving the chain. 我正在考虑一个新的类或方法,它可以接收这些值,存储它们,最后开始解析链。 But it would require to call an aditional method at the end, to init with the flow. 但它需要在最后调用aditional方法,以init为流程。

If you really wanted to create a chainable interface as in your question, this would do it: 如果你真的想在你的问题中创建一个可链接的界面,那么这样做:

 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); 

We just hide all the promise creation and chaining in an internal function. 我们只是隐藏了内部函数中的所有承诺创建和链接。 I split the code into smaller functions to make it a bit nicer looking. 我将代码分成更小的函数,使其看起来更漂亮。

You can try async and await 您可以尝试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(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM