비동기/대기 코드 (Typescript + es6 target)
을 어떻게 연결하여 Promise.then()
으로 변환합니까? 예를 들어일반 문자로 약속 연결하기
:
function mockDelay<T>(getValue:()=>T): Promise<T> {
return new Promise<T>(resolve=>setTimeout(()=>resolve(getValue()), 10));
}
// Assume blackbox implementation
class Service {
constructor(private i=1, private callCount=0){}
opA() : Promise<number> {
this.callCount++;
return mockDelay(()=>this.i+=1);
}
opB(value:number) : Promise<number> {
this.callCount++;
return mockDelay(()=>this.i+=value);
}
opC(): Promise<number> {
return mockDelay(()=>this.i+=2);
}
isA(): Promise<boolean> { return mockDelay(()=>this.callCount%2===0); }
isC(): Promise<boolean> { return mockDelay(() =>true); }
}
// Convert this async/await code to using chained Promises
async function asyncVersion(): Promise<string[]>{
let expected:string[] = [];
let lib = new Service();
let sum = 20;
let lastValue = 0;
while (sum > 0) {
expected.push(`${sum} left`);
if (await lib.isA())
{
expected.push("Do A()");
lastValue = await lib.opA();
sum -= lastValue;
}
else
{
expected.push("Do B()");
lastValue = await lib.opB(lastValue);
sum -= lastValue*3;
if (await lib.isC()) {
expected.push("Do C()");
sum += await lib.opC();
}
}
}
expected.push("All completed!");
return expected;
};
function chainPromiseVersion(): Promise<string[]>{
// How to convert the asyncVersion() to using chained promises?
return Promise.resolve([]);
}
// Compare results
// Currently running asyncVersion() twice to ensure call results are consistent/no side effects
// Replace asyncVersion() with chainPromiseVersion()
Promise.all([asyncVersion(), asyncVersion() /*chainPromiseVersion()*/])
.then(result =>{
let expected = result[0];
let actual = result[1];
if (expected.length !== actual.length)
throw new Error(`Length: expected ${expected.length} but was ${actual.length}`);
for(let i=0; i<expected.length; i++) {
if (expected[i] !== actual[i]){
throw new Error(`Expected ${expected[i]} but was ${actual[i]}`);
}
}
})
.then(()=>console.log("Test completed"))
.catch(e => console.log("Error: " + e));
나는 바벨 (Github example)를 사용하여 ES5하는 ES6 코드를 transpile 수 있습니다 알고 있습니다.
이 질문은 비동기/대기 코드를 사용하여 코드를 수동으로 다시 쓰는 것에 관한 것입니다.
다음과 같은 간단한 예를 변환 할 수 있습니다.
// Async/Await
(async function(){
for (let i=0; i<5; i++){
let result = await mockDelay(()=>"Done " + i);
console.log(result);
}
console.log("All done");
})();
// Chained Promises
(function(){
let chain = Promise.resolve(null);
for (let i=0; i<5; i++){
chain = chain
.then(()=>mockDelay(()=>"Done " + i))
.then(result => console.log(result));
}
chain.then(()=>console.log("All done"));
})();
그러나
어떻게 위의 경우의 예를 변환하는 아무 생각이 :- 루프 조건 약속의 결과에 영향을 한 후 - 더 - 다른 (어떤
Promise.all()
)
왜 당신이 원하는 것까지? – Bergi
방법을 알아보십시오. 나의 최종 목표가 단순히 async/es5를 목표로하는 코드를 기다리는 것이라면, 나는 Babel과 함께 이미 번쩍 거리고있을 것입니다. – jayars