2016-10-20 4 views
0

私はこのボタンをクリックした後、2つの異なる関数を実行するこの関数を持っています。 2番目の機能は前の機能に由来します。Typescriptと約束を使用して互いに隣り合った関数を実行する方法

processPayment(){ 
     console.log("payment called", this.registrationList); 
     this.registerLoading.present().then(() => { 
     //function1 
     this.sendRegistration().then(data => { 
      this.registerLoading.dismiss(); 
      this.paymentLoading.present().then(() => { 
      //function 2 
       this.sendPayments().then (data => { 
        this.paymentLoading.dismiss(); 
        this.nav.popToRoot(); 
        this.doAlert("Event Registration & Payments successful"); 
       }); 
      }); 
     }); 
     }); 
    } 

機能1:

sendRegistration(){ 
    return new Promise(resolve => { 
     for(let registration of this.registrationList){ 
      //codes removed for simplification 
      this.eventsService.postRegistration(eventRegistration) 
      .then(data => { 
       console.log("called", data); 
       this.invoices.push(data.Invoice.Id); 
      }); 
     } 
    }); 
    } 

機能2:

sendPayments(){ 
    return new Promise(resolve => { 
       //codes removed for simpplication 
     }); 
    } 

私はそれを順次実行するように見えるが、最初の関数は全く終了されていないので、私が見る傾けることを確認することができますが2回目の実行。

+0

あなたは「最初の関数は、すべてで終わるされていません」と言います。 'console.log(" data "と呼ばれる)が決して起こらないということですか?それは実際には関数コード、 '//単純化のために削除されたコード'に関連していますか? – enkryptor

答えて

0

あなたはチェーンと呼ばれる約束のフルパワーを使用する必要があります

processPayment(){ 
    console.log("payment called", this.registrationList); 
    this.registerLoading.present().then(() => { 
    //function1 
    return this.sendRegistration() 
    }).then(data => { 
    this.registerLoading.dismiss(); 
    return this.paymentLoading.present() 
    }).then(() => { 
    //function 2 
    return this.sendPayments() 
    }).then(data => { 
    this.paymentLoading.dismiss(); 
    this.nav.popToRoot(); 
    this.doAlert("Event Registration & Payments successful"); 
    }); 
} 

をしかし、あなたの本当の問題は、あなたがsendRegistrationで約束を解決することはありません、あなたはすべてのthis.postRegistrationの約束まで待機する必要があるので、あなたの場合には、それは複雑ですされます。すべての約束が完了するまで待つPromise.all()メソッドを使って行うことができます。

sendRegistration(){ 
    let allPostRegistrationPromises = []; 
    for (let registration of this.registrationList) { 
     //codes removed for simplification 
     let promise = this.eventsService.postRegistration(eventRegistration) 
     .then(data => { 
      console.log("called", data); 
      this.invoices.push(data.Invoice.Id); 
      return data; 
     }); 
     allPostRegistrationPromises.push(promise); 
    } 
    return Promise.all(allPostRegistrationPromises); 
} 

このコードはうまくいくはずですが、テストしませんでした。

あなたは本当に、この偉大な記事をお読みください約束がどのように動作するかを理解し、彼らの本当の力:https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

関連する問題