순차적으로 만드는 간단한 응용 프로그램에서 작업하고 있습니다. ajax 호출로 첫 번째 호출 결과를 다음 호출로 전달합니다.Q 약속 예제를 단순화하는 방법
물론 콜백 지옥에 들어가기를 원하지 않습니다. 이므로 Promises/A+ 사양 예와 Q library을 살펴보십시오.
필자는 원하는 결과를 가져 오는 비동기 함수를 준비했습니다. 하지만 Sequential promise를 단순화하는 방법에 대한 통찰력이 필요합니다.
지금은 약속과 지연된 객체를 가장 잘 사용하는 방법에 대해 계속 읽으므로 나를 매우 순진한 코드로 용서하십시오. 그래서
는 지금은 두 가지에서 찾고 있어요 (내 경우와 같이 하나의 서로에 따라) 약속의 순서
제안을 단순화하기 위해
- 방법
var modifyableObject = { toProcess : ["one", "two", "three", "four", "five"] } function returnsDeferredResults(someResult) { var deferred = Q.defer(); // my async function (setTimeout for now will do, $.ajax() later) setTimeout(function() { var nextResult = (someResult || " Initial_Blank_Value ") + "..." + modifyableObject.toProcess[0]; modifyableObject.toProcess = modifyableObject.toProcess.splice(1); console.log("New Tick Result: ", nextResult, "Array: ", modifyableObject.toProcess); deferred.resolve(nextResult); }, 200); return deferred.promise; } //$("#test_promise").click(function() { function getDeferredResult(prevResult) { return returnsDeferredResults(prevResult); } var prevResult = getDeferredResult(); var nextTick = ""; for (var i = modifyableObject.toProcess.length; i > 1; i --) { if (nextTick) nextTick = nextTick.then(getDeferredResult); else nextTick = prevResult.then(getDeferredResult); } //nextTick.fin(function(){ ...}); //}); /* New Tick Result: Initial_Blank_Value ...one Array: ["two", "three", "four", "five"] New Tick Result: Initial_Blank_Value ...one...two Array: ["three", "four", "five"] New Tick Result: Initial_Blank_Value ...one...two...three Array: ["four", "five"] New Tick Result: Initial_Blank_Value ...one...two...three...four Array: ["five"] New Tick Result: Initial_Blank_Value ...one...two...three...four...five Array: [] */
미리 감사드립니다. 당신은 너무 당신의 기능을 단순화 할 수
return modifyableObject.toProcess.reduce(function(promise, item) {
return promise.then(getDeferredResult);
}, Q.resolve());
var nextTick = getDeferredResult();
for (var i = modifyableObject.toProcess.length; i > 1; i --) {
nextTick = nextTick.then(getDeferredResult);
}
또는 :
return Q.delay(200).then(function) {
return "..." + modifyableObject.toProcess.shift();
});
jQuery를 AJAX
을하지 않습니다. 그들의 포인트는'modifyableObject'와 같은 전역 변수를 필요로하지 않아야합니다. – Bergi
이것은 간단하고 "전역"범위에 넣는 프로토 타입 코드 일뿐입니다. 'setTimeout' 함수 대신'$ .ajax()'를 사용할 것이고'modifyableObject'는'$ .ajax()'호출에 전달해야 할 데이터로 대체 될 것입니다. – Plyto