在回调函数中调用yield,为什么redux saga会给我一个异常?

4

所以我注释掉了会导致出现traceback的部分。

export function* watchFileReader(){
const action = yield take("DROP_FILE")
console.log('action', action)
let file = action.file[0];
readFile(file, function(e){
  sessionStorage.removeItem('img')
  console.log('alskdjfalsdjkf', e.target.result)
  sessionStorage.setItem('img', e.target.result)
  // yield put({type: "UDATE", {img: e.target.result})
   })
}

更新: 这是我的Promisified函数,可以使代码正常运行。
 function readFileWithPromise(file){
  return new Promise((resolve, reject) => {
   readFile(file, function(e){
     if (e){
      resolve(e)
     }else{
      reject(e)
     }
   })
 })
}
1个回答

5

您不能在回调函数中使用yield,有两种方法可以避免这种情况:

  1. cps effect . DOCS LINK

    import { cps , ...  } from 'redux-saga/effects';
    
    export function* watchFileReader(){
      const action = yield take("DROP_FILE")
      let file = action.file[0];
    
      let e = yield cps(readFile,file); <----------------
    
      sessionStorage.removeItem('img')
      sessionStorage.setItem('img', e.target.result)
      yield put({type: "UPDATE", img: e.target.result})
    }
    

    note : function must call cb(null, result) to notify the middleware of a successful result. If fn encounters some error, then it must call cb(error) in order to notify the middleware that an error has occurred.


  2. promisify your function

    function readFileWithPromise(file){
         return new Promise((resolve,reject)=>{
             readFile(file,(err, res) => err ? reject(err) : resolve(res));
        });
    }
    

    and then call it

    import { call, ...  } from 'redux-saga/effects';
    
    export function* watchFileReader(){
      const action = yield take("DROP_FILE")
      let file = action.file[0];
    
      let e = yield call(readFileWithPromise,file); <----------------
    
      sessionStorage.removeItem('img')
      sessionStorage.setItem('img', e.target.result)
      yield put({type: "UPDATE", img: e.target.result})
    }
    

两个示例的在线演示


我迫不及待想要在电脑前尝试一下。 - slopeofhope
谢谢,我使用 promisify 让它工作了。你太棒了! - slopeofhope

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接