0

我正在使用 Fingerprint2.js(现代灵活的浏览器指纹库,原始指纹库http://valve.github.io/fingerprintjs2/的继承者)

当我在函数内使用 console.log 时,我得到哈希指纹。但是当我将该结果存储在某个变量中时,它会给出“未定义”

Fingerprint2.get(options, function (components) {
  var values = components.map(function (component) { return component.value });
  console.log('insideFun -> ' + x64hash128(values.join(''), 31));
  return x64hash128(values.join(''), 31);
});

通过这个,我在我的控制台中看到了一个哈希码......但是如果我将返回值存储到一些var它不起作用。

如果我使用 asyn/await 它仍然执行控制台值但不存储var

var guid = function guid() {
    var fpid;
    var options = {}
    let fp = (async function() {
        const components = await Fingerprint2.getPromise(options);

        var values = components.map(function (component) { return component.value });

        let fpid = x64hash128(values.join(''), 31);
        return fpid;
     })();
  return fpid;
};

guid();

它给fpid is undefined

有没有办法处理这个?

4

1 回答 1

3

Fingerprint2.get是一个异步函数(这就是您需要为其提供回调的原因);在该回调中执行return ...不会有任何效果。

您可以getPromise改为使用返回 Promise,并使用 async/await 使您的代码看起来是同步的(即使不是):

// This function is asynchronous,
// it does not return a fp, but a Promise that will
// resolve to a fp
var guid = function guid() {
    const options = {};
    return Fingerprint2.getPromise(options)
           .then(components => {
             const values = components.map({ value } => value);
             return x64hash128(values.join(''), 31);
           });
};

// And then, there are 2 ways to use it:

// Method 1 - using `.then`
guid()
  .then(fpid => { // When it's done
    console.log(fpid); // Now you can use it
    document.cookie = `fpid=${encodeURIComponent(fpid)}`;
  });
  

// Method 2 - using `async/await`
(async function() {
  const fpid = await guid();
  console.log(fpid); // Now you can use it
  document.cookie = `fpid=${encodeURIComponent(fpid)}`;
})();

// But this will never work:
// const fpid = guid();
// console.log(fpid); // Promise<pending>

执行此操作时的问题:

const fpid = guid();
console.log(fpid);

...是console.log在检索指纹之前执行的。因为 FP2 是异步的。因此,您需要等待结果才能使用它。

于 2020-07-06T13:51:23.047 回答