Promises

Vladimir Dashukevich

Борьба с асинхронностью

Vladimir Dashukevich

...и я программист!

Цель

Асинхронность

Cамое большое расточительство?

Что-то напоминает?

I/O - медленно

Способы

Плюсы

Недостатки

Новый процесс

Плюсы

Недостатки

Потоки

Плюсы

Недостатки

Eventloop

Событийный цикл

Один поток = один стэк = одна функция

Heap (Куча)

Stack

Queue

Пример №2

Неожиданный клик

setTimeout(f, 1)

Мудрость №1

Короткие функции

Мудрость №2

setTimeout(f, 1)

Promise

Promise - объект, определяющий текущее состояние некой операции

loginPromise

                loginPromise.done(f1) === loginPromise
                loginPromise.then(f1, f2) !== loginPromise
            

Deferred

                new Promise(function(resolve, reject){
                	//resolve(results)	
                	//reject(error)	
                });
            
                (new Promise())
                	.then(loadImages)
                	.then(loadSounds)
                	.then(loadData)
                	.then(startGame)
            
                all([loadImages(), loadSounds(), loadData()])
                	.then(startGame)
            
                race([loadImages(), loadSounds(), loadData()])
                	.then(startGame)
            
                (new Promise())
                	.then(loadImages)
                	.then(renderImages)
                	.then(all([loadSound1(), loadSound2(), loadSound3()]))
                	.then(loadData)
                	.then(startGame)
            

Мудрость №3

Всегда возвращай promise

                (new Promise())
                	.then(getTrips, errorCallback)
                	.then(getCountries, errorCallback)
                	.then(getHotels, errorCallback)
                	.then(getRooms, errorCallback)
            

Cache

                getHotels()
                	.then(doSmth, errorCallback)
            

Где взять promise?

Библиотеки

Back to the future

ES6 и генераторы

                var gen = function* count(){
                	for (var x = 0; true; x++) {
                		yield x
                	}
                }
            
                var a = gen()
                a.next(); // => 0
                a.next(); // => 1
                a.next(); // => 2
            
                function* showFeed(){
                	var countries = yield getCountries();
                	renderCountries(countries);
                	var hotels = yield getHotels();
                	renderHotels(hotels);
                	var rooms = yield getRooms();
                	renderRooms(rooms);
                }
            

Вопросы?