javascript - 如何防止 promise 在没有箭头功能的情况下丢失上下文

标签 javascript promise

我有以下代码...

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

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

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

我收到错误,因为在 page.isLoaded 中,this 的上下文更改为 promise 。

有没有办法可以在没有箭头函数的情况下完成后面的操作?

最佳答案

正确使用 Promise。箭头表示法没有什么太冗长的,但一个好的做法是确保为任何 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() ,这通常表明您在确保正确性方面与 JavaScript 作斗争,而不是利用 JavaScript 让您确保正确的各种方式范围)

关于javascript - 如何防止 promise 在没有箭头功能的情况下丢失上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51070759/

相关文章:

javascript - 使用 Aria-Expanded 切换类

Javascript Onclick 按钮 - 取消第二次点击时执行的操作

javascript - 从 Promise.then/promise.catch 中获取原始函数名称

javascript - angular js结合了异步和同步代码

javascript - 什么是覆盖 promise 解决的值(value)的好方法?

javascript - jQuery 表和存储值问题

javascript - 使用 alert() 调试 autoproxy (PAC) javascript?

javascript - 从 Jquery post 请求切换到现代 Promise

javascript - 如何在客户端显示套接字io对象值?

javascript - 递归创建 Promise 时如何避免内存泄漏?