将 Key/Value 附加到 Promise 内部的对象

Appending Key/Value to object inside of Promise

所以我目前正在尝试使用下面的代码修改承诺中的全局对象,但是,当我 console.log 最后的对象时,它 returns 'undefined' 对于'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);
                })
            }
          })

console.log(patient) // yields

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

承诺是异步的。在 .then() 完成执行后,您只会在 patient 上看到 id 键。顶层代码是同步执行的,所以你在 promise 完成之前寻找 id 。当承诺已保证完成时,您只能在 .then() 等链式回调中访问 id

I'm a little confused as to why inside the success block of a promise it isn't setting the new key and value within the patient object.

但是,它不会立即执行。这就是承诺的工作方式。

当您的代码为 运行 时,它首先开始查找患者的过程。然后 运行 就是你的 console.log。当数据库查询完成后,它 运行 调用你的 .then 函数,它设置了 id。 设置patient.id之前console.log是运行。

如果您将 console.log(patient) 放在 then 中,紧跟在 patient.id = success.id 之后,您应该会看到正确的结果。

如果将它放在 catch 之后的 then 函数中,您将得到相同的结果(阅读有关 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
      })