我想使用带有异步函数的redux-saga yield call 效果来获取此函数的结果。 (在这种情况下是fingerprintjs,但它是一般情况)
这是我想要的异步函数:
new Fingerprint2().get(function(result, components) {
console.log(result) // a hash, representing your device fingerprint
console.log(components) // an array of FP components
})
我想通过saga执行此函数的问题,但它总是停留在yield调用上。
我尝试了很多方法:
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
}));
任何人都知道想法或某种方式来实现我的目标吗?
谢谢!
答案 0 :(得分:0)
yield
可以接受承诺。
const {result, components} = yield new Promise(resolve => {
new Fingerprint2().get(function(result, components) {
resolve({result, components})
})
})
答案 1 :(得分:0)
对于任何想回答这个问题的人,都有一些服务选择:
使用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