如何使用带有异步回调函数的 redux-saga

how to use redux-saga with async callback function

我想使用 redux-saga yield call effect with async function that get the result of this function is call back. (在这种情况下是 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
}));

有人知道实现我的目标的想法或方法吗?

谢谢!

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