2016-11-08 119 views
-1

因此,我目前正在嘗試使用下面的代碼修改promise中的全局對象,但是,當我在末尾使用console.log對象時,它會返回'undefined' 'id'的關鍵。我有點困惑,爲什麼在承諾的成功範圍內,它並沒有在患者對象內設置新的關鍵和價值。提前致謝!將Promise的對象添加到對象

patient = { first_name: first_name, last_name: last_name, gender: gender, dob: dob } 

     postgres.findPatient(patient) 
      .then(function(success){ 

      patient.id = success.id 

      }) 
      .catch(function(err){ 
      if (err.received === 0) { 
       postgres.createPatient(patient) 
       .then(function(success){ 
        postgres.findPatient(patient) 
        .then(function(success){ 
         patient.id = success.id 
        }) 
       }) 
       .catch(function(err){ 
        if (err) console.log(err); 
       }) 
      } 
      }) 

console.log(patient) // yields 

patient = { 
     first_name: 'billy, 
     last_name: 'bob', 
     gender: 'm', 
     dob: '1970-01-01' } 
+0

的[?我如何返回從一個異步調用的響應(可能的複製http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-異步調用) –

+0

嘗試console.log對象*在末尾*,而不是在您開始異步調用之後。 – Bergi

回答

0

承諾是異步的。在.then()執行完畢後,您只能看到patient上的id鍵。頂級代碼是同步執行的,所以您在承諾完成之前正在尋找id。當承諾保證完成時,您只能在.then()之類的鏈接回調中訪問id

2

我有點困惑,爲什麼在一個承諾的成功塊內,它不是在病人對象內設置新的鍵和值。

但是,它並不立即執行。這就是承諾如何工作。

當您的代碼運行時,它首先開始尋找患者的過程。然後它運行你的console.log。當數據庫查詢完成後,它會運行您的.then函數,該函數設置該ID。 console.log在設置patient.id之前運行。

如果您將console.log(patient)置於then之後,就在patient.id = success.id之後,您應該看到正確的結果。

如果將then函數放在catch之後(詳見Promise Chaining),您將得到相同的結果。這可能是編寫依賴於id的代碼的最佳位置。就像這樣:

patient = { first_name: first_name, last_name: last_name, gender: gender, dob: dob } 

    postgres.findPatient(patient) 
     .then(function(success){ 

     patient.id = success.id 

     }) 
     .catch(function(err){ 
     if (err.received === 0) { 
      postgres.createPatient(patient) 
      .then(function(success){ 
       postgres.findPatient(patient) 
       .then(function(success){ 
        patient.id = success.id 
       }) 
      }) 
      .catch(function(err){ 
       if (err) console.log(err); 
      }) 
     } 
     }) 
     .then(function() { 
     console.log(patient); 

     // Do something with the id 
     }) 
+0

非常感謝Ryan,這非常有意義! –

+1

很好的答案。我相信這被稱爲[Chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Chaining) – styfle

+0

@styfle是的,編輯答案補充說鏈接。謝謝! – RyanZim