Koa / Co / Bluebird 또는 Q / Generators / Promises / Thunks 상호 작용? (Node.js)
부분적으로 Koa로 웹 앱을 구축하는 것을 조사하고 있지만 지원하는 "비 동기화를 더 쉽게 만드는"기술 / 접근의 범위를 선택하고 적용하는 방법,시기 및 이유에 대해서는 잘 모릅니다 ( 아래 나열된).
전반적으로이 주제에 대한 웹상의 이질적인 지침은 특히 진화하는 모범 사례 또는 적어도 더 나은 사례와 관련하여, 어떤 시나리오에서 여전히 모호하게 남아 있습니다. 모든 것을 문맥에 담는 웹상에는 거의 또는 전혀없는 것 같습니다.
나는이 큰 엉덩이에 대한 응답이 그것을 수정할 수 있기를 바랍니다 . 또한 아래 질문은 누군가가이 문제를 해결하기 위해 철저한 블로그 게시물 등을 작성하도록 영감을 줄 수 있습니다. 내 감각은 그것으로부터 이익을 얻을 유일한 사람과도 가깝지 않다는 것입니다.
따라서 밝은 커뮤니티가 아래 나열된 기술 (굵은 글씨체)과 관련하여 다음 질문에 답변하고 명확성을 제공 할 수 있다면 기쁩니다.
-a) 어떻게 그리고 어떤 상황에서 (해당되는 경우) 서로 보완, 보충, 대체 및 / 또는 솔루션을 서로 겹치는가?
-b) 속도 성능, 오류 처리 용이성 및 디버깅 용이성과 관련하여 장단점은 무엇입니까?
-c) 언제, 어디서, 왜 "이"대 "저"기술, 기술-결합 및 / 또는 접근 방식을 사용하는 것이 더 좋을까요?
-d) "희미한 별"이 될 수있는 기술 또는 접근 방식.
(답변의 일부인 의견을 잘 설명 할 수 있다는 호핑.)
=============================
기술 :
* 코아 *
내 이해 :
Koa는 ECMAScript-6 기능 (특히 생성기 기능 중 하나)을 활용하도록 설계된 빌드 노드 앱의 최소 기반입니다.
* 공동 *
내 이해 :
-Co는 ECMAScript-6 생성기 (Node .011 하모니 기본)를 실행하기위한 유틸리티 라이브러리로, 생성기를 실행하고 관리하기위한 상용구 코드를 작성해야하는 필요성을 일부 / 많이 (?) 조율하는 것을 목표로합니다.
-Co는 본질적으로 Koa (?)의 일부입니다.
구체적인 질문 :
-코아가 아닌 컨텍스트에서와 다르게 코아에서 Co를 사용하는 경우와 방법. 즉, Koa는 전적으로 Co를 파사드합니까?
-더 나은 것이 있거나 있다면 Koa에서 Co를 다른 생성기 라이브러리로 대체 할 수 있습니까? 거기 아무도 없나요?
* "Q"및 Bluebird와 같은 Promise 라이브러리 *
내 이해 :
-Node가 기본적으로 해당 사양을 실행할 때까지 Promises / A + 사양을 구현하기위한 "폴리 필"입니다.
-Bluebird의 promisfyAll 유틸리티와 같이 사용 약속을 촉진하기위한 추가 비 사양 편의 유틸리티가 있습니다.
구체적인 질문 :
-내 이해는 ECMAScript-6 사양이 Promise / A + 사양을 크게 반영한다는 것입니다.하지만 그렇더라도 Node 0.11v 조화는 기본적으로 Promise를 구현하지 않습니다. (정확한가요?)하지만 그럴 때 Q, Bluebird와 같은 기술이 출시 될까요?
- "Q"와 Bluebird가 생성기를 지원하는 효과에 대해 읽었습니다. 이것은 무엇을 의미 하는가? 예를 들어, 그들이 Co와 동일한 효용을 어느 정도 제공했다는 것을 부분적으로 의미합니까? 그렇다면 어느 정도입니까?
* 썽크와 약속 *
나는 그들이 무엇인지에 대해 공정한 핸들을 가지고 있다고 생각하지만 누군가가 각각이 무엇인지에 대한 간결하고 명확한 "엘리베이터 피치"정의를 제공 할 수 있기를 바라며, 물론 위에서 요청한 바와 같이 서로를 사용할 때를 설명 할 수 있기를 바랍니다. Koa 맥락에서가 아니라 그것에서.
구체적인 질문 :
-Bluebird의 promisfy와 같은 것을 사용하는 것과 Thunkify (github com / visionmedia / node-thunkify)를 사용하는 것에 대한 장단점?
=============================
이 게시물과 그 질문에 대한 추가 컨텍스트를 제공하기 위해 다음 웹 페이지에 제시된 Koa 기술을 논의하고 대조 할 수 있다면 흥미로울 수 있습니다 (특히 장단점 기준).
-a) www.marcusoft. net / 2014 / 03 / koaintro.html (Thunks 또는 Promise는 어디에 있습니까, 아니면 뭔가 보이지 않습니까?)
-b) strongloop. com / strongblog / node-js-express-introduction-koa-js-zone (다시 말하지만 썽크 또는 약속은 어디에 있습니까?)
-c) github. com / koajs / koa / blob / master / docs / guide.md ( "next"인수는 무엇과 동일하며, 무엇을 설정하고 어디에 설정합니까?)
-d) blog.peterdecroos. com / blog / 2014 / 01 / 22 / javascript-generators-first-impressions (Koa 컨텍스트가 아니지만 Promise 라이브러리 (Bluebird)와 함께 Co 사용을 제공하므로 여기에 제시된 기술 / 패턴이 빌려 준다고 가정합니다. 그 자체로 Koa (?)에서 사용하는 것이라면 얼마나 좋을까요?
모두 감사합니다!
나는 거의 한 달 동안 발전기로 거의 광범위하게 일해 왔기 때문에 아마도 이것을 찌를 수 있습니다. 나는 의견을 최소한으로 유지하려고 노력할 것입니다. 혼동을 명확히하는 데 도움이되기를 바랍니다.
모범 사례와 더 나은 설명이없는 이유 중 하나는이 기능이 여전히 javascript에서 새로운 기능이기 때문입니다. firefox는 표준에서 약간 벗어 났지만, 제너레이터 node.js와 firefox가 가장 눈에 띄는 곳을 사용할 수있는 곳은 여전히 거의 없습니다.
트레이서 및 재생기와 같은 도구를 사용하여 개발에 사용할 수 있고 반등가 ES5로 전환 할 수 있다는 점에 유의하고 싶습니다. 따라서 작업이 즐겁다 고 생각되면 사용하지 않을 이유가 없습니다. 구식 브라우저를 목표로하고 있습니다.
발전기
생성기는 원래 비동기 제어 흐름을 처리하는 방법으로 생각되지 않았지만 훌륭하게 작동합니다. 생성기는 본질적으로 yield 사용을 통해 실행을 일시 중지하고 다시 시작할 수있는 반복기 함수입니다.
yield 키워드는 본질적으로이 반복에 대해이 값을 반환한다고 말하며, next ()를 다시 호출 할 때 중단했던 부분을 다시 선택하겠습니다.
생성기 함수는 처음 호출 할 때 실행되지 않고 대신 몇 가지 메서드가있는 반복기 객체를 반환하고 for-of 루프 및 배열 이해에서 사용할 수있는 기능이라는 점에서 특수 함수입니다.
send () ,: 이것은 yield의 마지막 값으로 취급하는 생성기로 값을 보내고 다음 반복을 계속합니다.
next () ,: 생성기의 다음 반복을 계속합니다.
throw () : 생성기에 예외가 발생하여 생성자가 마지막 yield 문에서 나온 것처럼 예외를 throw합니다.
close () : 생성기가 강제로 실행을 반환하고 필요한 경우 최종 오류 처리를 트리거 할 수 있도록 생성기의 finally 코드를 호출합니다.
일시 중지 및 재개 기능은 흐름 제어를 관리하는 데 매우 강력합니다.
공동
Co was built around the ability of generators to make handling flow control easier. It doesn't support all of the things that you can do with generators but you can use most of them through it's usage with less boilerplate and headache. And for flow control purposes I haven't found that I needed anything outside of what co provides already. Although to be fair I haven't tried sending a value into a generator during flow control but that does bring up some interesting possibilities....
There are other generator libraries out there some of them that I can think of off the top of my head are suspend, and gen-run. I've tried them all and co offers the most flexibility. Suspend may be a little easier to follow if you're not accustomed to generators yet but I can't say that with authority.
As far as node and best practices go I'd say co is currently winning hands down with the amount of support tools that have been created to go with it. With suspend the most likely runner up.
Co works with both promises and thunks and they are used for yield statement so that co knows when to continue execution of the generator instead of you manually having to call next(). Co also supports the use of generators, generator functions, objects and arrays for further flow control support.
By yielding an array or an object you can have co perform parallel operations on all of the yielded items. By yielding to a generator or generator function co will delegate further calls to the new generator until it is completed and then resume calling next on the current generator, allowing you to effectively create very interesting flow control mechanisms with minimal boilerplate code.
Promises
While I said I'd keep opinions to a minimum I would like to state that to me promises are probably the hardest concept to grasp. They are a powerful tool for maintaining code but they are hard to grasp the inner workings of and can come with quite a few gotchas if used for advanced flow control.
The easiest way that I can think of to explain promises is that they are an object returned by a function that maintains the state of the function and a list of callbacks to call when the a specific state of the object is or has been entered into.
The promise libraries themselves won't be going anywhere anytime soon. They add a great deal of nice to haves for promises included done() which didn't make it into the ES6 spec. Not to mention the fact that the same libraries can be used on the browser and in node we'll have them for a good long while.
Thunks
Thunks are just functions that take a single parameter callback and return another function that they are wrapping.
This creates a closure that allows the calling code to instantiate the function passing in its callback so that it can be told when the method is complete.
Thunks are fairly straight forward to understand and use in my opinion but they aren't the right tool for everything. For example spawn is a major pain to create a thunk for, you can do it but it's not easy.
Thunks vs. Promises
These aren't mutually exclusive and can easily be used together, but it's usually better for your sanity to pick one and stick with it. Or at the very least pick a convention so you can easily tell which is which. Thunks run faster from my experience but I haven't benchmarked it. Most of this is probably because it's a smaller abstraction and doesn't have error handling mechanisms built in.
You'll usually be building something that requires error handling though so the overall performance gains of thunks could easily even out or side in the favor of promises depending on your code.
When to Use
Generators - When you can safely say that your application will be able to run on the bleeding edge, whether it's firefox only for the browser or node > 0.11.3
I've been using them extensively at the company I'm out now and couldn't be happier with the control flow mechanisms and lazy evaluation that they allow.
Promises vs. Thunks - This is really up to you and how comfortable you are working with each. They don't provide the same benefits nor do they solve the same problem. Promises help deal with the async problem directly, thunks just ensure a function takes the needed callback parameter for other code to pass in.
You can use them both together and as long as you can keep it so that it's obvious which is which you won't have a problem.
Promises/Thunks with Generators - I suggest doing this anytime you are using generators for control flow. It's not necessary but it's easier just like using co as an abstraction for control flow with generators is easier. Less code to type, easier maintenance, and less possibilities that you'll hit an edge case that somebody else hasn't run into yet.
Koa
I'm not going to go into a lot of detail on koa. Suffice it to say that is similar to express but written to take advantage of generators. This does give it some unique advantages such as easier error handling and cascading middleware. There were ways to accomplish all of these tasks before but they weren't elegant and sometimes not the most performant.
Special Note: Generators open up a door of possibilities that we really haven't explored yet. Just like they can be used for control flow when that wasn't their initial design I'm positive they can be used to solve a lot of other problems that we normally have problems with in javascript. It will probably be brighter minds than me that find out how else we can use them but I'd at least start playing around with them and getting a better understanding of what they're capable of. There's still more goodies for generators coming in ES.next.
'Development Tip' 카테고리의 다른 글
RequireJS로 지연 로딩을 달성하는 방법은 무엇입니까? (0) | 2020.12.05 |
---|---|
Boost 속성 트리 write_json이 모든 것을 문자열로 저장하는 이유는 무엇입니까? (0) | 2020.12.05 |
AAR에 전 이적 종속성이 포함될 수 있습니까? (0) | 2020.12.05 |
xargs는 bash 별칭을 인식하지 못합니다. (0) | 2020.12.05 |
Windows Vista에서 Visual Studio 캐시를 어떻게 지우나요? (0) | 2020.12.04 |