首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将Fingerprint2结果保存在变量中

将Fingerprint2结果保存在变量中
EN

Stack Overflow用户
提问于 2020-07-06 21:45:50
回答 1查看 772关注 0票数 0

我使用的是Fingerprint2.js (现代灵活的浏览器指纹库,是最初的fingerprintjs http://valve.github.io/fingerprintjs2/的后继者)

当我在函数中使用console.log时,我得到了散列指纹。但是当我将结果存储在某个变量中时,它会给出'undifined‘

代码语言:javascript
复制
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

代码语言:javascript
复制
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

有什么办法解决这个问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-06 21:51:23

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

你可以使用getPromise来返回一个Promise,并使用async/await让你的代码看起来像是同步的(即使它不是同步的):

代码语言:javascript
复制
// 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>

这样做的问题是:

代码语言:javascript
复制
const fpid = guid();
console.log(fpid);

..。是在检索FingerPrint之前执行console.log。因为FP2是异步的。所以你需要等待结果,然后才能使用它。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62757452

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档