Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138249

Is there a way to convert a callback function into a generator in JavaScript?

$
0
0

I am using Axios to call an api endpoint which has a progress indicator. I would like to convert the onUploadProgress to a generator.

Is there a way to convert this code

setProgress({ state: 'syncing', progress: 0 });

await axios.post(uri.serialize(parsedURI), body2, {
    headers: { session_id: sessionId },
    onUploadProgress: (progress) => {
        setProgress({ state: 'syncing', progress: progress.loaded / progress.total });
    },
});
setProgress({ state: 'syncing', progress: 1 });

Into something like this

yield { state: 'syncing', progress: 0 };

await axios.post(uri.serialize(parsedURI), body2, {
    headers: { session_id: sessionId },
    onUploadProgress: (progress) => {
        yield { state: 'syncing', progress: progress.loaded / progress.total };
    },
});
yield { state: 'syncing', progress: 1 };
await new Promise(resolve => setTimeout(resolve, 100));

the problem is in the yield inside the onUploadProgress, I was thinking there could be a way to use it like when you want to convert a callback into a promise you use

new Promise(resolve => fn(resolve));

maybe there is some valid way of doing it for generators like

new Generator(next => fn(next));

Viewing all articles
Browse latest Browse all 138249

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>