2017-11-27 4 views
0

현재 경쟁 조건에 조금 싫증이났습니다. 머리카락을 뽑아 내고 있습니다. 기본적으로 API를 쿼리하고 DB에 결과를 추가 한 다음 반환 된/저장된 데이터로 작업을 수행합니다.약속 및 경쟁 조건

나는이 특정 문제에 대해 덜 궁금해하고 있으며, 이런 종류의 문제를 해결하는 방법에 대한 디자인 패턴이 더 많습니다. 줄 p.push(formatter.createAccounts(account, id));은 최대 1000 회까지 실행될 수 있으며 20 초 정도 걸릴 수 있습니다.

내가

덕분에 매우 도움이 될 것입니다 잘못하고있는 무슨에 어떤 아이디어, 올리


// get all users 
Promise.all(updatedUsers) 
.then(() => { 
    // create an array of promises 
    const p = []; 

    users.then((user) => { 
    ... 
    ids.forEach((id) => { 
     const accounts = foo.getAccounts(id, true); // returns a promise 
     accounts.then((account) => { 
     // add the return data from here to the promise array at the bottom 
     p.push(formatter.createAccounts(account, id)); 
     }); 
    }); 
    }); 

    // this would ideally be a promise array of the data from above - but instead it just evaluates to [] (what it was set to). 
    Promise.all(p).then(() => { 
    // do my stuff that relies on the data here 
    }) 
}); 
+0

'사용자'와 'ids'는 어디에서 오는가? –

+0

어쩌면 일부 일관된 샘플 코드를 게시 할 수 있습니다. 현재 구문 오류가 있으며 변수의 절반이 어디에서 왔는지는 분명하지 않습니다. – Tomalak

+0

[내 변수를 함수 내부에서 수정 한 후 왜 변수가 변경되지 않습니까? - 비동기 코드 참조] (https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –

답변

2

문제는 당신이 당신의 약속을 배열에 foo.getAccounts 약속을 포함하지 않는 것입니다 . 수정 된 버전 :

Promise.all(updatedUsers) 
.then(() => { 

    users.then((user) => { 
    return Promise.all(ids.map(id => { 
     //for each ID we return a promise 
     return foo.getAccounts(id, true).then(account => { 
     //keep returning a promise 
     return formatter.createAccounts(account, id) 
     }) 

    }).then((results) => { 
     //results is an array of the resolved values from formatter.createAccounts 
     // do my stuff that relies on the data here 
    }) 
    }) 

//rest of closing brackets 
+1

'p' 변수를 없앨 수 있습니다. – JLRishe