2017-02-02 32 views
0

私は約束が新しく、2つの約束をどのように組み合わせるのかを掴むのに苦労します。私は約束を解決し、いくつかのタスクを行う機能を持っている:別の約束の中で約束を解決する

loginService (context, credentials) { 
    context.$http.post(LOGIN_URL, credentials, { emulateJSON: true}).then(response => { 
    this.user.authenticated = true 
    localStorage.setItem(TOKEN_STORAGE_NAME, response.body[TOKEN_NAME]) 
    }).catch(response => { 
    context.error = response.body 
    }) 
}, 

をそして私は、私は次のような何かを行うことができるように上記のコードを変更したい:

適切何
login() { 
    this.submitButtonLoading = true 
    loginService(this, this.credentials).then(response => { 
    this.submitButtonLoading = false 
    // Do something else here. 
    }).catch(response => { 
    this.submitButtonLoading = false 
    // Do something else here. 
    }) 
} 

これを処理する方法は?

+1

関数には 'return'ステートメントが必要です。 – 4castle

答えて

1

戻る約束loginServiceから、あなたが連鎖を維持することができます:loginthen()機能が常に実行されること

loginService (context, credentials) { 
    return context.$http.post(LOGIN_URL, credentials, { emulateJSON: true}) 
    .then(response => { 
     this.user.authenticated = true 
     localStorage.setItem(TOKEN_STORAGE_NAME, response.body[TOKEN_NAME]) 
    }) 
    .catch(response => { 
     context.error = response.body 
    }) 
} 

login() { 
    this.submitButtonLoading = true 
    loginService(this, this.credentials) 
    .then(_ => { 
     this.submitButtonLoading = false 
     // ... 
    }) 
} 

注意、呼び出しが成功したかどうかに関係なく。

+0

パーフェクト、ありがとう!私はそれを試みましたが、それが成功するかどうかを区別できませんでした。それがどうかどうかを処理する方法はありますか? – hatzipanis

+0

@hatzipanis promise chain内のどこにでもスローされたキャッチされていないエラーは、存在する場合には 'catch'ハンドラに直接伝播します。さもなければ、エラーは静かに呑み込まれますので、常に 'catch'を使用してください。 –

+0

@ JaredSmithありがとう!あなたは例を投稿できますか? – hatzipanis

0

loginServiceを約束するには、関数内にPromiseを返します。機能が完全に満たされている場合は、resolveおよび/またはrejectに電話してください。あなたの例では

、次のことができます。

var loginService = function(context, credentials) { 
    return new Promise((resolve, reject) => { 
    context.$http.post(LOGIN_URL, credentials, {emlateJSON: true}) 
     .then(response => { 
     if (success) { 
      this.user.authenticated = true 
      resolve(this.user) 
     } else { 
      reject(new Error('Log in failed')) 
     } 
     }) 
     .catch(err => { 
     reject(err) 
     }) 
    }) 
} 

は、今では当時のことができます。

実際、関数全体が実際に大きなPromiseを返すことに注意してください。また、成功または失敗がどのように解決または拒否されるかに注目してください。

+0

[$ http.post](https://github.com/pagekit/vue-resource)メソッドはすでに約束を返すように見えますが、これが何らかの反パターンを作ります。 – traktor53

+0

ありがとう@ Traktor53私はこのルートを下り始め、それが実現しているかもしれないことに気付きました。 – hatzipanis