제 질문은 약속을 구축하는 함수에 컨텍스트와 인수를 모두 전달해야 할 때 BlueBird에있는 약속의 우아한 병렬화에 관한 것입니다.병렬 약속의 유체 구성
내 문제를 이해하고 테스트 할 수 있도록하기 위해 종속성이없는 예제를 만들었습니다.
비동기 "컴퓨터"(자원을 해제해야 함)가 관련된 계산 (1/(x x x) + 1/(x * x))을 가정 해 봅니다. 사각형과 큐브는 비동기 적으로 독립적으로 계산됩니다.
나는이처럼 내 계산을 수행 할 수 있습니다
InitComputer(2) // returns a promise
.then(invert)
.then(function(arg){
return Promise.all([
proto.square(arg),
proto.cube(arg)
]);
}).spread(function(sq, cu){
this.set(sq + cu);
}).catch(function(err){
console.log('err:', err);
}).finally(endComputer);
하지만 이론적으로는 가능 것과 비교 all
너무 무거운의 사용을 찾을 수 있습니다. then
에 인수로 함수를 전달하면 실행됩니다. all
에 함수를 전달할 때 오류가 발생합니다.
InitComputer(2)
.then(invert)
.all([
proto.square,
proto.cube
]).spread(function(sq, cu){
this.set(sq + cu);
}).catch(function(err){
console.log('err:', err);
}).finally(endComputer);
: 나는
이 스타일의 간단한 무언가로 변경하는 솔루션이 있나요 ... 내가 유틸리티 또는 패턴을 누락 의심?나는 아마도 Promise.prototype.all을 해킹하거나 다형성을 증가시키지 않으려는 새로운 기능을 정의 할 수 있지만 소유하지 않은 객체의 수정과 관련없는 솔루션에만 관심이 있습니다.
부록 :
여기 내 테스트에 대해 "컴퓨터"를 정의하는 방법은 다음과 같습니다 당신이 Promise.all
를 사용할 필요가 없습니다
var Promise = require("bluebird");
function Computer(){}
function InitComputer(v){
// initializing a computer is asynchronous and may fail hence the promise
var c = new Computer(), resolver = Promise.defer();
setTimeout(function(){
if (v>1) resolver.resolve(v);
else resolver.reject(new Error("bad value: "+v));
},100);
return resolver.promise.bind(c);
}
var proto = Computer.prototype;
proto.square = function(x){
// imagine this really uses the computer and is asynchronous
if (!this instanceof Computer) throw new Error('not a computer');
return x*x
}
proto.cube = function(x){ return x*x*x }
proto.set = function(v){ this.value = v }
function endComputer(){
// releases resources here
console.log('value:', this.value);
}
// this asynchronous function doesn't involve or know the computer
function invert(v){ return 1/v }
뭔가 잘못을 받고 있지만, 때로 믿을 수 있습니다 'proto.square (arg)'와'proto.cube (arg)'는 즉시 평가되고, 결과는'Promise.all'에 대한 배열 생성자로 전달됩니까? (편집) 오, 오케이, 그들은 아마 비동기, 결코 마음이 있어야합니다. – Groo
@ 그 라우 바로. * "실제로 컴퓨터를 사용하고 비동기식이라고 상상해보십시오"*. 질문을 읽을 수 있도록 최소한의 코드를 만들었으므로 몇 가지 바로 가기를 사용해야했습니다. –