2017-02-11 4 views
1

개별적인 문제를 처리하기 위해 각자에게 then/catch 조건을 첨부하고자하는 수많은 약속을 생성하는 자바 스크립트에 상황이 있습니다.JSHint, for 루프, 약속 및 하나의 성가신 린트 오류

모든 약속이 해결 된 시점을 결정하기 위해 allSettled을 사용할 수있게 해주는 RSVP Promise 라이브러리를 사용하고 있습니다. RSVP의 allSettled은 모든 성공한 약속의 끝과 실패한 약속의 출력에 대한 평가를 제공하지만 각 약속에 then/catch을 추가하여 특정 약속이 충족되지 않으면 어떻게해야 좋을지를 제어 할 수 있습니다 예를 들어, 실패한 사용자 만 사용하여 다시 시도하라는 메시지 등).

내 믿음직한 린터 (JSHint), 나는 점점 계속 사용 "Don't make functions within a loop."나에게 다시 소리, 나는 정말 자르기 린트 이런 종류의 오류없이 각각의 약속에 then/catch 조건을 첨부 할 수 있어야합니다.

JSHint 규칙을 변경하는 것 외에도 다른 사람들이 JSHint 오류를 어떻게 다루는 지 궁금합니다. 좋은 규칙이라고 생각합니다. 누군가 내 생성 된 약속을 처리하는 방법에 대해 더 잘 알고 있다면, then/catch 유스 케이스. 여기

은 예입니다 :

let Promise = RSVP.Promise 
 
let people = ['Marty McFly', 'Doc', 'Robocop', 'Terminator', 'Bozo'] 
 
let sendMessagesToPeople = [] 
 
let thoseSucceeded = [] 
 
let thoseFailed = [] 
 

 
// Dummy Promise method to send a message to a person 
 
function sendMessageToPerson (person, msg) { 
 
    console.log(`Sending message to ${person}...`) 
 
    return new Promise((resolve, reject) => { 
 
    setTimeout(() => { 
 
     if (Math.random() > 0.5) { 
 
     console.log(`✔︎ Sent "${msg}" to ${person}`) 
 
     resolve(person, msg) 
 
     return 
 
     } 
 
     console.log(`✘ Failed sending "${msg}" to ${person}`) 
 
     reject(person, msg) 
 
    }, 1000 + (Math.random() * 2000)) 
 
    }) 
 
} 
 

 
// Generate the array of Promises for allSettled to process 
 
for (let i = 0; i < people.length; i++) { 
 
    let trySendMessageToPerson = sendMessageToPerson(people[i], "Hi there!") 
 
    /* Illegal, according to JSHint */ 
 
    .then(() => { 
 
     thoseSucceeded.push(people[i]) 
 
    }) 
 
    .catch(() => { 
 
     thoseFailed.push(people[i]) 
 
    }) 
 

 
    sendMessagesToPeople.push(trySendMessageToPerson) 
 
} 
 

 
RSVP.allSettled(sendMessagesToPeople).then(() => { 
 
    console.log(`Succeeded: ${thoseSucceeded.length}, Failed: ${thoseFailed.length}`) 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/rsvp/3.3.3/rsvp.min.js"></script>

편집 :

나는 for, forEachmap 그래서 답변을 사용으로 성능 차이에 관해서는 정말 궁금해서 @rasmeister와 @hacker에 의해 주어진다. rdave 좀 더 확대됨에 있던 루프 확인할하려고하는 JSPerf 테스트를 고안 (나는 또한 재미를위한 while 시험에 던졌다) : 내이 결과가 격렬하게 다를 매우 결정적이다 테스트에서 https://jsperf.com/for-foreach-map-while-loop-performance-testing

, 그래서 나는이 어떤 루프 구현이 성능 측면에서 더 나은지는 알 수 없지만 가독성 측면에서 보면 map 옵션을 사용해야한다고 생각합니다.

답변

0

let Promise = RSVP.Promise 
 
let people = ['Marty McFly', 'Doc', 'Robocop', 'Terminator', 'Bozo'] 
 
let thoseSucceeded = [] 
 
let thoseFailed = [] 
 

 
// Dummy Promise method to send a message to a person 
 
function sendMessageToPerson (person, msg) { 
 
    console.log(`Sending message to ${person}...`) 
 
    return new Promise((resolve, reject) => { 
 
    setTimeout(() => { 
 
     if (Math.random() > 0.5) { 
 
     console.log(`✔︎ Sent "${msg}" to ${person}`) 
 
     resolve(person, msg) 
 
     return 
 
     } 
 
     console.log(`✘ Failed sending "${msg}" to ${person}`) 
 
     reject(person, msg) 
 
    }, 1000 + (Math.random() * 2000)) 
 
    }) 
 
} 
 

 
let sendMessagesToPeople = people.map((person) => { 
 
    return sendMessageToPerson(person, "Hi there!") 
 
    .then(() => { 
 
     thoseSucceeded.push(person) 
 
    }) 
 
    .catch(() => { 
 
     thoseFailed.push(person) 
 
    }) 
 
}) 
 

 
RSVP.allSettled(sendMessagesToPeople).then(() => { 
 
    console.log(`Succeeded: ${thoseSucceeded.length}, Failed: ${thoseFailed.length}`) 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/rsvp/3.3.3/rsvp.min.js"></script>

이것은 당신이 다음 m 모두에 응답 할 수 배열로 약속을 수집하는 것입니다.

0

당신은 루프에서 함수 정의를 제거해야 - 당신은 forEach 다음에 그것을 사용, 하나 개의 함수로 루프의 모든 로직을 추출 할 수 있습니다 :

people.forEach(sendMessage); 

function sendMessage(person) { 
    let trySendMessageToPerson = sendMessageToPerson(person, "Hi there!") 
    .then(thoseSucceded.push) 
    .catch(thoseFailed.push); 

    sendMessagesToPeople.push(trySendMessageToPerson); 
} 
0

당신은 두 함수를 정의 할 수있는 다음

let addSuccess = person => thoseSucceeded.push(person); 
let addFailure = person => thoseFailed.push(person); 

을 ... 그리고 :

한 번만 - thencatch에 전달되는 - 그리고 지금은 각 반복에 정의되어 있습니다
let trySendMessageToPerson = sendMessageToPerson(people[i], "Hi there!") 
    .then(addSuccess) 
    .catch(addFailure)