简体   繁体   English

ES6产生多个发电机

[英]ES6 yield multiple generators

In ES6 yield and generator function allow to await once function will execute. 在ES6中,产量和发电机功能允许等待一旦功能执行。 But I want to await multiple generators. 但我想等待多个发电机。 Here the code: 这里的代码:

files.forEach(function* (file) {
    const uploadedFile = yield call([service, service.upload], file, config)
}

call is redux-saga effect callredux-saga效应

To express the Saga logic we yield plain JavaScript Objects from the Generator. 为了表达Saga逻辑,我们从Generator生成纯JavaScript对象。 We call those Objects Effects 我们称之为对象效果

I want to fire all uploads in one time, without waiting before previous finished and wait once all files got uploaded, is it possible with yield ? 我想一次性触发所有上传,无需等待上一次完成并等待所有文件上传后,是否可以获得yield

What I was looking for was actually this: 我真正想要的是这样的:

// correct, effects will get executed in parallel
const [users, repos]  = yield [
  call(fetch, '/users'),
  call(fetch, '/repos')
]

call here is just returning promise 这里的call只是回归承诺

When we yield an array of effects, the generator is blocked until all the effects are resolved or as soon as one is rejected (just like how Promise.all behaves). 当我们产生一系列效果时,生成器被阻塞,直到所有效果都被解决或者一旦被拒绝(就像Promise.all行为一样)。

You can use Promise.all() instead 您可以使用Promise.all()代替

EXAMPLE: 例:

If you want to fire all uploads and regain control of the code after they all finished you can use async/await interface: 如果要在完成所有上传后重新启动对代码的控制,可以使用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)

Your "call" method should return a Promise object, otherwise you have to wrap it into Promise. 你的“call”方法应该返回一个Promise对象,否则你必须将它包装到Promise中。

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

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