我使用的是Fingerprint2.js (现代灵活的浏览器指纹库,是最初的fingerprintjs http://valve.github.io/fingerprintjs2/的后继者)
当我在函数中使用console.log时,我得到了散列指纹。但是当我将结果存储在某个变量中时,它会给出'undifined‘
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。
有什么办法解决这个问题吗?
发布于 2020-07-06 21:51:23
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);..。是在检索FingerPrint之前执行console.log。因为FP2是异步的。所以你需要等待结果,然后才能使用它。
https://stackoverflow.com/questions/62757452
复制相似问题