javascript - JS this.function 不是 promise 中的函数
问题描述
我正在尝试处理一个队列,其中我正在调用一个查询 api 的类函数。但无论我尝试什么,我都会得到错误
Uncaught (in promise) TypeError: this.getVisitorData is not a function
这是我在 index.js 中的队列
# index.js
(async (ppc) => {
const lander = new landingPage();
// run the queued calls from the snippet to be processed
for (let i = 0, l = ppc.queue.length; i < l; i++) {
await lander.queue.apply(ppc, ppc.queue[i])
}
})(window.ppc)
这是类的landingPage queue 方法:
# landing_page.js
// process window.pcc queue
async queue(method, value, data) {
if (method === 'init') {
config.propertyId = value
} else if (method === 'event') {
// Do no track if visitor opted out
if (!await optOut()) {
new ppcEvent(value, data)
}
} else if (method === 'options' && value === 'visitor') {
const data = await this.getVisitorData()
this.customizeLander(data)
}
}
这是查询api的类landingPage方法
# landing_page.js
async getVisitorData() {
const key = 'landing_page_customization'
let visitor = helpers.isset(window.sessionStorage.getItem(key))
if (!visitor) {
try {
const [geo, device] = await axios.all([axios.get(config.geoEndpoint), axios.get(config.deviceEndpoint)]);
const visitor = {
...geo.data,
...device.data,
}
window.sessionStorage.setItem(key, JSON.stringify(visitor))
return visitor
} catch (err) {
console.log(err.message);
}
}
return JSON.parse(window.sessionStorage.getItem(key))
}
我什至尝试从 中删除异步visitorData
,但我看到了同样的错误。我在这里做错了什么?
解决方案
第一个参数apply()
是应该this
在被调用函数中的值。由于queue
是landingPage
类的方法,因此您应该将该类的实例作为第一个参数传递。显然ppc
不是landingPage
,而是lander
。所以将行更改为
await lander.queue.apply(lander, ppc.queue[i])
您还可以使用 ES6 扩展符号代替apply
:
await lander.queue(...ppc.queue[i]);
推荐阅读
- python - 如何在 spaCy v3 中正确使用变压器模型进行自定义 NER?
- notepad++ - 在我的用户定义语言中定义折叠标记时遇到问题
- javascript - 使用输入过滤器在长下拉列表中搜索项目,但只允许用户从下拉列表中提交选项
- python - 如何在 Google 我的地图中导入 CSV 文件?
- csv - 由于某种原因,附加到 CSV 失败
- azure-devops - Azure DevOps API 从发布 ID 获取所有测试运行
- sql - 根据同一表中另一列中的唯一值更新多行
- flutter - 使用flutter web将数据加载到firebase存储中的文件内存中
- java - 你什么时候会在 postgres 可序列化隔离级别上使用 Hibernate 乐观锁?
- javascript - 如何在 HTML 中重叠两个 div(登录时的成功消息)?