javascript - 使用异步方法覆盖函数原型,保留此上下文
问题描述
在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()
解决方案
选项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())
推荐阅读
- python - 使用 read_excel() 在 pandas 中读取文件时面临问题
- javascript - 如何使用 redux 为 react js 设置加载状态
- javascript - 使用函数计算倒数计时器的剩余时间与仅使用变量
- c# - Task.WaitAll/WhenAll 与批处理执行和结果返回函数一起使用的正确方法
- pine-script - 如何存储前一个交易日的数据(枢轴),并将它们绘制为当前今天交易时段的水平?
- java - 我们无法打开名称中带有空格的图像 Tomcat
- c++ - 为什么位域的无符号整数在 C++ 中的移位操作后变成有符号整数?
- javascript - 如何在将num值转换为单词后显示“仅”单词
- java - 如何在不等待线程完成的情况下精确渲染帧
- android - 如何从本地网络中的其他设备向我的移动 http 服务器发送请求?