TypeError: fpPromise.then is not a function

183 views Asked by At

I want to using fingerprintjs to get the device id. this is the typescript code looks like:

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;

when I run this code, shows error:

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

I traced the code and found fpPromise is not null. why did this happen? how to fixed this problem? the fingerprintjs version is:

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

this is how to invoke this function in typescript "ttypescript": "^1.5.13",:

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

the node version is v16.13.2.

1

There are 1 answers

0
samthecodingman On BEST ANSWER

Importing a module inline using import() will return Promise<FingerprintJS> (because it's asynchronous). Importing a module inline using require() will return FingerprintJS directly (because it's synchronous).

For your application, to match the documentation's first sample, you should replace:

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

with

// here, fpPromise is a Promise<Agent> object
const fpPromise = require('@fingerprintjs/fingerprintjs').load();