Thursday 4 May 2017

Best practice when using co inside a ES6 class, generator or just normal function?

Generally when I need to define functions inside of a class, there is no difference between these 2 approaches below:

const co = require('co')
const request = require('co-request')
class Test{
    some_async_func1(){
        return co(function *() {
            let response = yield request('http://www.google.com');
            return response;
        })
    }

    *some_async_func2(){
        let response = yield request('http://www.google.com');
        return response;
    }
}

If I call the function like

let test = new Test();

    co(function *() {

        let response1 = yield test.some_async_func1();
        console.log(response1.statusCode);

        let response2 = yield test.some_async_func2();
        console.log(response2.statusCode);

    })

They simply act the same.

I am so wondering which is a better way to struct my code?

It looks like approach1's logic fully integrates with co and hard to clean up. But we sometimes also face the condition that we need to call some async "private" function like below.

some_action_after_login(){

    return co(function *() {
            yield this.login();
            return yield request('https://myaccount.google.com');
    })
}

I am so curious if there is a "standard" code structure to deal with this problem.

Thanks in advance.



via abuuu

No comments:

Post a Comment