1

我想使用fingerprintjs来获取设备ID。这是打字稿代码的样子:

const DeviceHandler = {
    getDeviceId: async (): Promise<string> => {
        return new Promise((resolve, reject) => {
            // Initialize an agent at application startup.
            const fpPromise = require('@fingerprintjs/fingerprintjs');

            // Get the visitor identifier when you need it.
            fpPromise
                .then((fp: { get: () => any; }) => fp.get())
                .then(async (result: { visitorId: any; }) => {
                    // This is the visitor identifier:
                    const deviceId = result.visitorId;
                    resolve(deviceId);
                });
        });
    }
};

export default DeviceHandler;

当我运行此代码时,显示错误:

background.js:5253 Uncaught (in promise) TypeError: fpPromise.then is not a function
    at background.js:5253:26
    at new Promise (<anonymous>)
    at background.js:5248:35
    at step (background.js:5240:23)
    at Object.next (background.js:5221:53)
    at background.js:5215:71
    at new Promise (<anonymous>)
    at background.js:5211:12
    at Object.getDeviceId (background.js:5246:39)
    at background.js:4811:108

我跟踪了代码,发现fpPromise它不为空。为什么会这样?如何解决这个问题?指纹版本是:

"@fingerprintjs/fingerprintjs": "^3.3.2",

这是在 typescript 中调用此函数的方法"ttypescript": "^1.5.13",

import DeviceHandler from "@utils/data/DeviceHandler";
const deviceId = await DeviceHandler.getDeviceId();

节点版本是v16.13.2.

4

1 回答 1

3

使用内联导入模块import()将返回Promise<FingerprintJS>(因为它是异步的)。使用内联导入模块require()FingerprintJS直接返回(因为它是同步的)。

对于您的应用程序,要匹配文档的第一个示例,您应该替换:

// here, fpPromise is a FingerprintJS object - not a Promise!
const fpPromise = require('@fingerprintjs/fingerprintjs');

// here, fpPromise is a Promise<Agent> object
const fpPromise = require('@fingerprintjs/fingerprintjs').load();
于 2022-02-19T04:03:24.463 回答