tj / co

The ultimate generator based flow-control goodness for nodejs (supports thunks, promises, etc)
MIT License
11.87k stars 795 forks source link

Make primitive types yieldable #293

Open tzlAsTom opened 7 years ago

tzlAsTom commented 7 years ago
const co = require('co');

function delay(seconds){
    if(!(seconds > 0)) return 0;

    return new Promise( (resolve, reject) => {
        setTimeout( () => resolve(seconds), seconds * 1000);
    });
};

return co(function* (){
    let rtn;
    rtn = yield delay(1);
    console.log('rtn1', rtn);
    rtn = yield delay(0);
    console.log('rtn0', rtn);
    return rtn;
}).then( (result) => {
    console.log('result', result);
}).catch( (error) => {
    console.error('error', error);
});

Will get:

[tong@localhost test]$ node genTest.js
rtn1 1
error TypeError: You may only yield a function, promise, generator, array, or object, but the following object was passed: "0"

Expect:

[tong@localhost test]$ node genTest.js
rtn1 1
rtn0 0
result 0
cmazakas commented 7 years ago

This should be: if(!(seconds > 0)) return Promise.resolve(0);

Mixing return types in an un-typed language like JS is just asking for maintainability and debugging nightmares. By returning a synchronous Promise, you keep the structure of the code relatively the same and don't introduce any sort of type-handling (was I returned a Promise or a primitive?)