我想使用带有异步函数的 redux-saga yield 调用效果,该函数的结果是回调。(在这种情况下,指纹JS,但这是一般情况(
这是我想要确切的异步函数:
new Fingerprint2().get(function(result, components) {
console.log(result) // a hash, representing your device fingerprint
console.log(components) // an array of FP components
})
我想通过 saga 执行此功能的问题,但它总是卡在收益调用上。
我尝试了很多方法:
import Fingerprint2 from 'fingerprintjs2';
const func = new Fingerprint2().get;
const res = yield call(func);
也可以像这样尝试:
import Fingerprint2 from 'fingerprintjs2';
const func = new Fingerprint2().get;
const a = yield call(func, (fingerprint, result) => ({
fingerprint,
result
}));
像这样:
import Fingerprint2 from 'fingerprintjs2';
let res = yield call(new Fingerprint2().get(), (fingerprint, result) => ({
fingerprint,
result
}));
有人知道想法或实现我的目标的方法吗?
谢谢!
yield
可以接受Promise。
const {result, components} = yield new Promise(resolve => {
new Fingerprint2().get(function(result, components) {
resolve({result, components})
})
})
对于任何想要回答这个问题的人,都有薮猫选项:
使用 CPS:
const { result, components } = yield cps(cb => new Fingerprint2().get((result, components) => cb(null, { result, components })))
有承诺:
function* rootSaga(){
// Wrapping you function into a promise
const promise = new Promise((resolve, reject) => {
new Fingerprint2().get((result, components) => {
resolve({ result, components })
})
})
// Yield the promise And redux-saga will return the resolved value when the promise resolves
const { result, components } = yield promise
// do some stuff about result and components ...
}
信用:Redux-Saga GitHub