簡體   English   中英

拒絕承諾中的處理

[英]reject handling in promises

以下代碼從每個getJSON方法返回一個RSVP承諾:

  getJSON('/login')
  .then(getJSON('/errors').then(function(users) {
    self.user = users;
  }))
  .then(getJSON('contacts').then(function(contacts) {
    self.contacts = contacts;
  }))
  .then(getJSON('companies').then(function(companies) {
    self.companies = companies;
    callback(self);
  }, function(err){
    console.log('does not get here')  
  }));

我對Promise的理解顯然是錯誤的,我不想為每個then提供錯誤回調,而是我認為該錯誤將被轉發到隨后的then函數之一中的下一個可用錯誤回調。

在上面的代碼中,第2行的getJSON將被拒絕,但是在最后一個回調中不會轉發到錯誤回調上。

然后,我是否必須為每個錯誤回調提供回調。 這似乎與回調地獄沒有什么不同。

您是否有理由不一次提出所有請求?

self.user = getJSON("login");
self.contacts = getJSON("contacts");
self.companies = getJSON("companies");
// not sure what "/errors" does or what you assign it to, add it if you please

//.hash will go through object properties and wait for all promises to resolve
return RSVP.hash(self).then(function(results){
    //here, self now contains .user .contacts and .companies
    callback(self); //DO NOT do this, instead return the promise
}).catch(function(err){
     //this is where all error handling goes
});

注意return那里,這是最好的回報的承諾,而不是調用回調函數,你可以.then從外面。

我認為您在錯誤地履行諾言。 您的getJSONS在上一個完成之后沒有連續執行。 調用第一個getJSON(getJSON('/ login'))時,沒有將兩個處理程序傳遞給then方法。 您正在傳遞一個新的getJSON調用。 這意味着,在對getJSON的調用完成之后(但在ajax調用結束之前),您正在執行第二個getJSON(getJSON('/ errors'))。 您將傳遞的結果作為getJSON('/ login')then方法的第一個參數傳遞。 這樣,此承諾將以與getJSON('/ errors')相同的值來解析或拒絕。 好吧...

.then(getJSON('companies').then(function(companies) {
    self.companies = companies;
    callback(self);
  }, function(err){
    console.log('does not get here')  
  }));

在這里,您正在傳遞一個新的諾言,它是getJSON(companies)返回的諾言,作為then方法的第一個參數。 該方法所屬的Promise在被拒絕時將嘗試調用作為第二個參數傳遞的函數...但是沒有! 因此,因為getJSON('companies')不會拒絕,所以您不會收到錯誤。 我已經重寫了您的鏈:

getJSON('/login').then(
  function(users) {
      self.user = users;
      return getJSON('/errors');
  }).then(function() {
      return getJSON('contacts')
  }).then(function(contacts) {
      self.contacts = contacts;
      return getJSON('companies');
  }).then(function(companies) {
      self.companies = companies;
      callback(self);
  }, function(err){
    console.log('does not get here')  
  });

現在,我認為它應該工作正常。 在成功完成每個承諾的解析之后,將執行發出新的getJSON請求的函數,並且它將返回其承諾。 如果其中任何一個拒絕,拒絕將一直進行到找到帶有第二個參數的then為止,這發生在鏈的末尾。 最后一個函數(err)將捕獲在此之前發生的所有錯誤。

與本傑明·格林鮑姆(Benjamin Gruenbaum)相似,但更為簡潔。

return RSVP.hash({
  user: getJSON("login");
  contacts: getJSON("contacts");
  companies: getJSON("companies");
}}).then(callback).catch(function(err){
     //this is where all error handling goes
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM