【问题标题】:how to use redux-saga with async callback function如何使用带有异步回调函数的 redux-saga
【发布时间】:2018-09-26 07:04:06
【问题描述】:

我想将 redux-saga yield call 效果与异步函数一起使用,该函数的结果是回调。 (在这种情况下是指纹,但它是一般情况)

这是我想要精确的异步函数:

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 call 上。

我尝试了很多方法:

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
}));

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

谢谢!

【问题讨论】:

    标签: reactjs redux-saga fingerprintjs2


    【解决方案1】:

    对于任何想回答问题的人,有多种选择:

    与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

    【讨论】:

      【解决方案2】:

      yield 可以接受 Promise。

      const {result, components} = yield new Promise(resolve => {
        new Fingerprint2().get(function(result, components) {
          resolve({result, components})
        })
      })
      

      【讨论】:

      • 谢谢,它的工作,但我有一个问题:有没有一种方法来实现这一点而不用承诺包装它?我尝试使用 cps 但它也是堆栈。