2016-11-08 118 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