简体   繁体   中英

Calling yield in callback, redux saga gives me an exception why?

so I commented out where it gives me a 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})
   })
}

update: this is my promisified function to get the code to work.

 function readFileWithPromise(file){
  return new Promise((resolve, reject) => {
   readFile(file, function(e){
     if (e){
      resolve(e)
     }else{
      reject(e)
     }
   })
 })
}

you can't use yield in callback , there are two ways to avoid this:

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

LIVE DEMO for two examples

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM