首页 > 解决方案 > 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,但我看到了同样的错误。我在这里做错了什么?

标签: javascriptasync-awaites6-class

解决方案


第一个参数apply()是应该this在被调用函数中的值。由于queuelandingPage类的方法,因此您应该将该类的实例作为第一个参数传递。显然ppc不是landingPage,而是lander。所以将行更改为

await lander.queue.apply(lander, ppc.queue[i])

您还可以使用 ES6 扩展符号代替apply

await lander.queue(...ppc.queue[i]);

推荐阅读