2016-10-21 11 views
0

ネストされた約定を避けるために、次のような方法を最適化するにはどうすればよいですか?それは動作しますが、私は約束を入れ子にし続けるつもりですネストされた約束を最適化する

コードは最初に認証してサービスを返します。そして、サービスを非同期に呼び出してアイテムを取得する関数にそのサービスを送ります。

new Promise(function(resolve, reject) { 
    auth.authenticate(resolve); 
}).then(function(service) { 
    console.log('service', service); 
    new Promise(function(resolve, reject) { 
     lineItems.getLineItems(service, resolve, reject); 
    }).then(function(items) { 
     console.log('returned line items'); 
     console.log(items); 
    }).catch(function(err){ 
     console.log('error!', err); 
    }); 
}); 
+1

auth.authenticate() .then((service) => lineItems.getLineItems(service)) .then((items) => console.info('Items:',items)) .catch((err) => console.error(err)); 

auth.authenticateおよび/またはlineItems.getLineItemsは外部にあり、かつ標準nodejs callbak /エラーバックスタイルに従っている場合、あなたは約束を返すためにこれらの機能をラップすることができますあなたが[返品]していないのでエラーが発生しやすいです(http://stackoverflow.com/questions/37081508/resolving-an-array-of-promises-from-within-a-parent-promise/37084467#37084467)二番目の約束。 – jib

答えて

1

ちょうどthenから新しい約束を返す:

new Promise(function(resolve, reject) { 
    auth.authenticate(resolve); 
}).then(function(service) { 
    console.log('service', service); 
    return new Promise(function(resolve, reject) { 
     lineItems.getLineItems(service, resolve, reject); 
    }); 
}).then(function(items) { 
    console.log('returned line items'); 
    console.log(items); 
}).catch(function(err){ 
    console.log('error!', err); 
}); 

をまた、あなたはプロを返すようにlineItems.getLineItemsを調整することができれば後の項目は、おそらく非同期呼び出しを含む別の関数を呼び出します

new Promise(function(resolve, reject) { 
    auth.authenticate(resolve); 
}).then(function(service) { 
    console.log('service', service); 
    return lineItems.getLineItems(service); 
}).then(function(items) { 
    console.log('returned line items'); 
    console.log(items); 
}).catch(function(err){ 
    console.log('error!', err); 
}); 
+0

このようにして約束を作成し、解決/拒否を機能に渡すことは良い習慣ですか?それとも、私が最初に約束すると呼んでいる機能の方が良いでしょうか? – darkace

+2

'lineItems.getLineItems'があなたによって設計されている場合、IMOは' resolve'と 'reject'を渡すために冗長です。議論として 'サービス'だけを取って約束を返すようにしてください。したがって、返す新しいPromise(function(resolve、... ' –

+0

)の代わりにlineItems.getLineItems(service);を返すことができます。それをあなたの答えに追加することができればそれを受け入れるでしょう:) – darkace

1

私は、主に機能の定義方法にいくつかの問題があります。実際には、コードで定義されている非同期関数の非標準のシグネチャが原因です。

auth.authenticateおよびlineItems.getLineItemsがあなたによって書かれている場合は、これらの機能を更新して適切なPromiseを返します。その後、組成物は次のようになります。このコード

const authenticate = Promise.promisify(auth.authenticate, {context:auth}); 
const getLineItems = Promise.promisify(lineItems.getLineItems,{context:lineItems}); 

authenticate() 
    .then(getLineItems) 
    .then((items) => console.info('Items:',items)) 
    .catch((err) => console.error(err)); 
関連する問題