繁体   English   中英

我如何防止没有箭头功能的承诺丢失上下文

[英]How do I prevent promises from losing context without arrow function

我有以下代码...

page.goToPage().then(() => page.isLoaded()).then(() => driver.quit());

这似乎太冗长,但是当我尝试...

page.goToPage().then(page.isLoaded).then(driver.quit);

我得到的错误,因为在page.isLoaded的背景下this改变的承诺。

有没有办法不用箭头功能就可以做以后的事情?

正确使用承诺。 箭头符号没有什么太冗长的,但是一个好的实践是确保向then任何处理程序提供执行任务所需的信息。

class Driver {
  quit() {
    console.log("quit");
  }
}

class Page {
  constructor() {
    this.driver = new Driver();
  }

  goToPage() {
    console.log("gotopage");
    return new Promise((resolve, reject) => {
      // Things happen here. If they go wrong, you call reject() with an argument that
      // is a useful error object. If they succeed, you call resolve() with data that the
      // next handler should be working with. In this case I'm passing "this" so that the
      // page is available to the next link in the chain.
      resolve(this);
    });
  }

  waitForLoad() {
    console.log("waitforload");
    return new Promise((resolve, reject) => {
      // let's have this fail half the time, for demonstration purposes.
      var l = Math.random();
      if (l < 0.5) {
        resolve(this.driver);
      } else {
        reject(new Error("error"));
      }
    });
  }
}

现在,您具有适当的使用promise的代码:

var p = new Page();

p.goToPage()
 .then( page => page.waitForLoad())
 .then( driver => driver.quit())
 .catch( e => console.error(e));

每个then处理现在得到它到底需要调用它需要调用的函数,没有试图通过自己的范围,胸围的输入,而不必.bind()什么。

(如果您需要普通代码中的.bind() ,通常这就是您在确保Sope方面与JavaScript作战的标志,而不是利用JavaScript可以确保正确范围的各种方式)

就像迈克(Mike)在找到答案后建议的那样,它似乎并不那么冗长...

page.goToPage()
    .then(page.isLoaded.bind(page))
    .then(driver.quit.bind(driver));

(感谢@GetOffMyLawn)

如果有人有创造性的解决方案,我将不回答这个问题。

暂无
暂无

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

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