2016-12-31 1 views
3
const a = [1, 2, 3, 4, 5]; 

const f =() => new Promise((resolve, reject) => resolve(4)); 

const g =() => { 
    Promise.all(a.map((member) => f().then((res) => res))) 
    .then((result) => { 
     console.log(result) 
    }); 
} 

g(); 

가 여기에 {return res;}에 연결된 다른 필요하지 않습니다?NodeJS 약속 해상도

나는 그 안에 return (something)이있을 때 또 다른 then을 첨부해야한다고 읽었지 만 여기서는 그렇지 않습니다. 도움?

+1

당신이지도, 또는 flatMap하도록 구성하면 약속 알아낼 것입니다. 그래서 당신은 평범한 가치를 돌려 줄 수 있고 그것은지도로 나타낼 것입니다; 약속을 되풀이하면 평평해질 것입니다. – elclanrs

답변

3

Promise.all은 일련의 약속을 기대합니다. .then 약속을 반환합니다. 따라서 매핑 논리는 숫자 배열을 약속의 배열로 정확하게 변환합니다.

.then((res) => {return res;})은 완전히 불필요합니다. return f();이면 충분합니다. 당신은에 더 현재의 코드를 단순화 할 수 있습니다

Promise.all(a.map(f)).then(result => console.log(result)); 

나는 당신이 then 내부 return (something)이있을 때, 또 다른 다음

.then 함께 할 수 없다

를 첨부해야 함을 읽어 보시기 바랍니다. .then은 단순히 약속을 반환합니다. .then을 통해 처리기를 연결해야하는 결과 인에 액세스하십시오.

약속을 Promise.all으로 전달하기 때문에 여기서는이 작업을 수행 할 필요가 없습니다. 에 을 (를) 통해 결과가 표시됩니다.

+0

"map (f)"에 "return"을 두지 않은 이유가 무엇입니까? – user7361276

+0

'(member) => {return f();}'는 예제에서'f'와 동일합니다. 더 일반적인 : 주어진'function foo() {}; function bar() {return foo(); }'그리고 나서'bar()'를 호출하는 것은'foo()'를 직접 호출하는 것과 똑같습니다. 예제에서, 중간 함수'(member) => {return f();}'에 대한 필요가 없기 때문에'a.map'에'f'를 직접 전달할 수 있습니다. –

0

여기에 {return res;}에 다른 사람이 필요하지 않은 이유는 무엇입니까?

나는 그 안에 return (something)이있을 때 또 다른 then이 첨부되어야한다고 읽었지 만 여기서는 그렇지 않습니다. 도움?

에는 또 다른 .then()이 붙어 있습니다. Uncaught (in promise)을 피하기 위해 을 첨부해야합니까?

또한 Promise.all()return이 아니며 g()에서 전화하여 Promise을 더 체인으로 연결합니다. .map() 콜백 체인 내에

.then().catch() 핸들 오류 중 하나를 이용하거나 거부 Promise 반환 될 수 Promise.all() 체인 .then()-Promise 해결; 또는 throw 현재 또는 신규 Error()에서 Promise.all()으로 전화하십시오.

패턴

은 즉시 Promise.all()에 체인 .catch()를 호출하지 않고, 해결 또는 .then() 거부 ​​여부, .map()에 전달 된 모든 약속을 반환하는 데 사용할 수 있습니다.

function f (index) { 
 
    return new Promise(function (resolve, reject) { 
 
     if (index !== 4) resolve(4); 
 
     else reject("err at index " + index) 
 
    }) 
 
} 
 

 
var a =[1, 2, 3, 4, 5]; 
 

 
function g() { 
 
    return Promise.all(a.map((member, index)=>{ 
 
     return f(index).then((res) => {return res;}) 
 
       .catch(e => {console.log(e); throw new Error(e)}) 
 
    })) 
 
    .then((result)=>{console.log(result); return result}) 
 
    .catch(e => { 
 
     // handle error here, return resolved `Promise`, 
 
     // or `throw new Error(e)` to propagate error to 
 
     // `.catch()` chained to `g()` call 
 
     console.log("handle error within g", e); 
 
     return "error " + e.message + " handled"}); 
 
} 
 

 
g() 
 
.then(data => {console.log(data) /* `error err at 4 handled` */ }) 
 
.catch(e => console.log("done", e));

관련 문제