简体   繁体   English

在回调中调用yield,redux saga给了我一个例外原因?

[英]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: 你不能在回调中使用yield,有两种方法可以避免这种情况:

  1. cps effect . cps效应。 DOCS LINK 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. 注意:函数必须调用cb(null,result)来通知中间件成功的结果。 If fn encounters some error, then it must call cb(error) in order to notify the middleware that an error has occurred. 如果fn遇到一些错误,那么它必须调用cb(错误)才能通知中间件发生了错误。


  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 现场演示有两个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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