Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 27.07.2014, 12:39
Аватар для PeaceCoder
Профессор
Отправить личное сообщение для PeaceCoder Посмотреть профиль Найти все сообщения от PeaceCoder
 
Регистрация: 15.12.2009
Сообщений: 742

Simply fibers on yields
Привет всем!

Перейду сразу к делу. Я устал программировать на callback'ах и многих библиотеках похожих на промисы. Вот написал свою и прошу оценить удобность ее использования. 3 раза ее переписывал и окончательный вариант использования - выкладываю на обозрение.

Установка

npm install fybers


Использование:

var Fyber = require('../index');

function* generatorFunction(a,b){
    console.log('GeneratorFunction this & args:', this, arguments);

    return a * b;
}

var generatorInstance = generatorFunction(1,2);

function asyncFunction(a,b,cb){
    console.log('AsyncFunction this & args:', this, arguments);

    setTimeout(function(){
        cb(null, a + b);
    },1000);
}

// ***************** Creating a fyber ********************

var thisObj = {};

var fyber = new Fyber(generatorFunction, thisObj);
var fyber = new Fyber(generatorInstance);
var fyber = new Fyber(asyncFunction, thisObj);

console.log('**************** Synchronious usage fybers ***************');

var someObject = {

    prop: 25,

    asyncFnMethod: function(a, b, cb){
        cb(null, a - b * this.prop);
    },

    generatorFnMethod: function* (a, b){
        return a / b + this.prop;
    }

};

function* syncWork(a,b){

    //gets current fyber
    syncWork.fyber;

    //gets scope of current fyber
    syncWork.scope === syncWork.fyber.scope;

    console.log('This & args of syncWork:', this, arguments);

    // call async function with some this object
    var result1 = yield asyncFunction.call({someThisObj: true}, a, b, syncWork.cb);

    console.log('Async function result (30):', result1);  // 30

    // call generator function with some this object
    var result2 = yield generatorFunction.call({someThisObj2: true}, a, b);

    console.log('Generator function result (200):', result2);  // 200

    //call async method of someObject
    var result3 = yield someObject.asyncFnMethod(a, b, syncWork.cb);

    console.log('Async method result (-490):', result3); // -490

    //call generator method of someObject
    var result4 = yield someObject.generatorFnMethod(a,b);

    console.log('Generator method result (25.5):', result4); // 25.5

    return result1 + result2 + result3 + result4;
}

var work = new Fyber(syncWork, {thisObj: true});


work.on('done', function (error, result) {
    console.log('syncWork error & result (-234.5):',error, result); // -234.5
});

console.log('Start syncWork...');
work.start(10,20); // start work asynchroniusly
console.log('Started syncWork...');


Больше примеров - в папке examples
Видео мануал (на русском): https://drive.google.com/file/d/0B3E...it?usp=sharing
Описание API тут: http://habrahabr.ru/sandbox/85175/
__________________
Настоящий программист думает и осознает сам решение задачи, а не копирует другие мысли, не осознавая их (c)
Относись к человеку так же, как хотелось бы отношения к себе (с)
Все нужно там, где оно нужно, а все не нужно нигде (с) Gozar
B~Vladi: А кто такой JavaScript стрелок?! micscr: это тот, кто не jQuery танкист.
Программы становятся медленнее быстрее, чем компьютеры становятся быстрее (с) Никлаус Вирт

Последний раз редактировалось PeaceCoder, 28.07.2014 в 15:53.
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Аналог книги Simply JavaScript twolf Общие вопросы Javascript 2 20.07.2008 13:04