首页 > 解决方案 > 使用异步方法覆盖函数原型,保留此上下文

问题描述

在javascript中,如果我有这样定义的函数

function Person() {
}

Person.prototype.someFunction = function() {
  // Does soome logic
  return this
}

Person.prototype.anotherFunction = function () {
  // Does soome logic
  return this;
};


我想实现链接我会做这样的事情

const person = new Person();

person.someFunction().anotherFunction()

这在每个方法都返回 Person 的实例时起作用。

现在,如果我有一个具有一些异步操作的方法,我如何在异步方法中返回 this 实例

function someApiCall() {
  return new Promise((res) => {
    setTimeout(() => {
      res('got data');
    }, 2000);
  });
}


Person.prototype.asyncFunction = function () {
  someApiCall()
    .then()
    .catch()

  // HOW DO I RETURN THIS INSTANCE HERE ???? as someAPICALL is async
};

这样我就可以将其用作

person.someFunction().asyncFunction().anotherFunction()

标签: javascriptpromiseprototype

解决方案


选项1(不按顺序执行):

Person.prototype.asyncFunction1 = function () {
  someApiCall()
  .then((e) => console.log(e))
  .catch()

  return this;
};

p.anotherFunction().asyncFunction1().anotherFunction()

所有函数都被调用,但不是按顺序调用的。如果你想按顺序执行它,只需这样做:

选项2(按顺序执行):

Person.prototype.asyncFunction2 = async function () {
  const ans = await someApiCall();
  console.log(ans);
  return this;
};

// t represents this as you return it in asyncFunction2 
p.anotherFunction().asyncFunction2().then((t) => t.anotherFunction())

推荐阅读