Skip to content

Using generators as cancellable async functions

DigitalBrainJS edited this page Oct 17, 2021 · 1 revision

Using generators as cancellable async functions

Generally, you able to use CPromise with ES6 async functions, but if you need some specific functionality such as progress capturing or cancellation, you need to use generators instead of async functions to make it work. This is because the async function leads all the nested thenables into its own Promise class, and there is nothing we can do about it. Generators allow you to write asynchronous code just in the same way as async functions do, just use yield instead of await. See the live demo

import CPromise from "c-promise2";

const promise= CPromise.from(function*(){
    this.innerWeight(12); //optionally set the expected internal progress score of the nested chain
    yield CPromise.delay(1000);
    yield [CPromise.delay(1000), CPromise.delay(1500)] // resolve chains using CPromise.all([...chains]);
    yield [[CPromise.delay(1000), CPromise.delay(1500)]] // resolve chains using CPromise.race([...chains]);
    yield new Promise.resolve(); // any thenable object will be resolved 
    return "It works!";
})
.progress(value=> console.log(`Progress: ${value}`))
.then(message=> console.log(`Done: ${message}`));

Then method also supports generators as callback function

CPromise.resolve().then(function*(){
    const value1= yield CPromise.delay(3000, 3);
    // Run promises in parallel using CPromise.all (shortcut syntax)
    const [value2, value3]= yield [CPromise.delay(3000, 4), CPromise.delay(3000, 5)]
    return value1 + value2 + value3;
}).then(value=>{
    console.log(`Done: ${value}`); // Done: 12
}, err=>{
    console.log(`Failed: ${err}`);
})
Clone this wiki locally