将键/值附加到Promise内的对象

时间:2016-11-08 22:59:22

标签: javascript node.js es6-promise

所以我目前正在尝试使用下面的代码修改promise中的全局对象,但是,当我在最后控制对象时记录对象时,它返回' 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' }

2 个答案:

答案 0 :(得分: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
      })

答案 1 :(得分:0)

Promise是异步的。在id执行完毕后,您只会在patient上看到.then()键。顶级代码是同步执行的,因此您需要在承诺完成之前查找id。只有在保证完成承诺时,您才能访问id之类的链式回调中的.then()

相关问题