2017-11-27 20 views
0

私は現在競争状態に少し止まっていて、私は自分の髪を引っ張っています。基本的には、APIにクエリを実行し、結果をDBに追加してから、返された/保存されたデータを使って処理します。約束と競争条件

私はこの特定の問題について尋ねることは少なく、この種の問題を解決する方法の設計パターンはますます増えています。行p.push(formatter.createAccounts(account, id));は最大1000回まで実行され、20秒ほどかかります。

私は

おかげで超参考になります間違ってやって上の任意のアイデア、 Ollie第


// 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

'users'と' 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