[英]ES6 yield multiple generators
在ES6中,产量和发电机功能允许等待一旦功能执行。 但我想等待多个发电机。 这里的代码:
files.forEach(function* (file) {
const uploadedFile = yield call([service, service.upload], file, config)
}
call
是redux-saga效应
为了表达Saga逻辑,我们从Generator生成纯JavaScript对象。 我们称之为对象效果
我想一次性触发所有上传,无需等待上一次完成并等待所有文件上传后,是否可以获得yield
?
我真正想要的是这样的:
// correct, effects will get executed in parallel
const [users, repos] = yield [
call(fetch, '/users'),
call(fetch, '/repos')
]
这里的call
只是回归承诺
当我们产生一系列效果时,生成器被阻塞,直到所有效果都被解决或者一旦被拒绝(就像Promise.all行为一样)。
您可以使用Promise.all()代替
例:
如果要在完成所有上传后重新启动对代码的控制,可以使用async / await接口:
function uploadALL(files){
const uploadedFilesPromises = files.map( file => {
return call([service, service.upload], file
})
}
return Promise.all(uploadedFilesPromises);
}
// samples of using this function:
uploadALL(files).then((uploadedFiles)=> { .... })
// or in async function you can use await:
const uploadedFiles = await uploadAll(files)
你的“call”方法应该返回一个Promise对象,否则你必须将它包装到Promise中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.