我想要做一个函数,它能得到指纹2.js的结果。
Fingerprint2是一个现代灵活的浏览器指纹库http://valve.github.io/fingerprintjs2/用法:
new Fingerprint2().get(function(result, components){
console.log(result); //a hash, representing your device fingerprint
console.log(components); // an array of FP components
});
无论我如何尝试在new Fingerprint2().get(function(result, components){
之外获取Fingerprint2的结果,都失败了。比如全局变量和cookie,因为Fingerprint2().get(...)它是异步的吗?它可以像函数一样编写来获取fingerprint2结果吗?例如:
var secure = getmefingerprint2();
发布于 2020-01-28 10:44:45
利用ES2017 feature async/await
,您可以像这样使用Fingerprint2.getPromise()
:
(async () => {
const components = await Fingerprint2.getPromise();
const values = components.map(component => component.value);
const murmur = Fingerprint2.x64hash128(values.join(""), 31);
console.log('fingerprint:', murmur);
)()
请参阅Fingerprint2 Doc中的get和getPromise
发布于 2016-10-08 21:19:04
这应该是一个评论,但它有点长。
即使这是可能的,您也将绕过已发布的api,这意味着您将不得不维护原始代码的分支。您还需要同步调用该功能- fingerprintjs2异步运行的原因显而易见。
你好像是在问XY problem的事
您应该如何处理它取决于您打算在指纹被捕获后如何处理它。
发布于 2017-04-08 02:22:32
你不能让异步代码完全同步。但是,如果您目标浏览器支持supported,但它不是通用的,那么您可以使用async/await。而且,它只在async
函数内部看起来是同步的
其基本思想是返回一个promise,然后在async
函数中对其进行await
:
const getmefingerprint2 = async () => {
const secure = await (new Promise(resolve => {
new Fingerprint2().get((result, components) => resolve(result) )
}))
// do things with secure, whatever you return is thenable
return secure
}
该函数可以像这样调用(因为有了Promises):
getmefingerprint2().then(result => {
// do stuff with result
})
而且,在异步函数中,您可以像同步处理一样对待secure
。
如果你真的想让你的异步代码表现得更同步(如果你讨厌异步,可能对其他异步代码也很有用),你可以将所有代码包装在一个async
函数中,然后使用await
来获取异步内容:
const getFingerprint = () => new Promise(resolve => {
new Fingerprint2().get((result, components) => resolve(result) )
})
const main = async () => {
// do some of your app here
const secure = await getFingerprint()
// do more stuff here
}
main()
或作为IIFE
(async() => {
// do some of your app here
const secure = await getFingerprint()
// do more stuff here
})()
这些只是一些老生常谈的变通方法,可以让你摆脱异步代码的负担,这可能是值得了解的,因为它会做出更好的应用程序。如果您将代码重构为只在回调中包含依赖于secure
的内容,那么一旦您习惯了,就会获得更好的性能、畅通无阻的UI以及更易于理解的更动态的流程。
https://stackoverflow.com/questions/39932716
复制相似问题