2016-12-10 1 views
1

나는 해결할 수없는 다소 간단한 문제가 있습니다. 또한 google/stackoverflow에서 아무 것도 찾을 수 없습니다. (아마도 잘못된 키워드를 사용하고있는 것일까 요?)동적으로 약속 만들기

값의 배열이 있는데 그 배열의 모든 단일 요소에 대해 특정 함수를 호출하고 싶습니다. 까다로운 점은 함수가 약속을 반환하고 약속이 해결되면 다시 호출해야한다는 것입니다. 나는 이런 식으로 할 것, 나는이 약속을 기다리고되지 않을 것이다

다음 함수 호출하기 전에 해결해야합니다 :이처럼 그것을 할 것입니다 경우

let paramerterArr = ['a','b','c','d','e','f'] 
paramerterArr.forEach((currentParam) => { 
    let promise = mySpecialFunction(currentParam) 
}) 

가 나는를 작성해야

let paramerterArr = ['a','b','c','d','e','f'] 
mySpecialFunction(paramerterArr[0]).then(()=> { 
    return mySpecialFunction(paramerterArr[1]) 
}).then(()=> { 
    return mySpecialFunction(paramerterArr[2]) 
}).then(()=> { 
    return mySpecialFunction(paramerterArr[3]) 
}).then(()=> { 
    return mySpecialFunction(paramerterArr[4]) 
}).then(()=> { 
    return mySpecialFunction(paramerterArr[5]) 
}) 

내가 이런 식으로 할 것이라고해도 난 그냥 배열 변경할 수 있습니다 : :이처럼 그것을 할 것입니다 경우

을 난 그냥 내 배열을 변경할 수 없습니다 중복 코드의 많은 나는 중복 코드를 많이 작성해야하고 난 그냥 내 배열을 변경할 수 없습니다 :

let paramerterArr = ['a','b','c','d','e','f'] 
let currentPos = 0 
mySpecialFunction(currentPos).then(()=> { 
    currentPos++ 
    return mySpecialFunction(currentPos) 
}).then(()=> { 
    currentPos++ 
    return mySpecialFunction(currentPos) 
}).then(()=> { 
    currentPos++ 
    return mySpecialFunction(currentPos) 
}).then(()=> { 
    currentPos++ 
    return mySpecialFunction(currentPos) 
}).then(()=> { 
    currentPos++ 
    return mySpecialFunction(currentPos) 
}) 

이 어쩌면 당신의 사람이 아이디어를 가지고 난 그냥 그것을 할 수있는 현명한 방법을 생각할 수 없다

... , 그것은 좋을 것이다.

+0

여기를 참조하십시오 Array.reduce을 사용할 수 있습니다 시리즈에 약속을 실행하려면 - http://stackoverflow.com/documentation/javascript/231/promises/5917/reduce- 배열 간 연결 # t = 201612101336270481763 –

답변

2

당신이()

parameterArr.reduce(function(promise, item) { 
    return promise.then(function(result) { 
    return mySpecialFunction(item); 
    }) 
}, Promise.resolve()) 
+0

Q() 란 무엇입니까? – Forivin

+0

'Q()'는 promise chain을 킥 스타트하기위한 빈 약속 (Q lib를 사용 - 다른 약속 일 수 있음)이기 때문에'promise'를 줄이기 위해 전달 된 함수가'Q()'가됩니다. – hackerrdave

+0

약속 라이브러리를 사용하고 있지 않습니다. 네이티브 JS 약속 (ECMA6)을 사용하고 있습니다. 방금 대신 Promise() 또는 뭔가를 사용할 수 있습니까? – Forivin

관련 문제