如何在promise中正确设置对象值?

时间:2017-11-01 04:40:01

标签: javascript object

所以我有这个对象:

let user = {
    name: null,
    age: null,
    sex: null,
    created_at: null
}

我希望根据promise返回的值设置值。返回的数据具有相同的属性名称。

所以承诺是这样的:

promise.get(/*url*/).then(res => {
    const data = res.data;
    // set values here
})

我现在在设置属性值时有三种方法:

// First
user = data

// Second
user = {
    name: data.name,
    age: data.age,
    sex: data.sex,
    created_at: data.created_at
}

// Third
Object.assign(user, data);

哪种方式最好?一个优于另一个的优势是什么?  我目前正在使用第三种选择。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

我喜欢Object.assign()

    const user = {
      name: 'Ronald Mickdonlad',
      age: null,
      sex: 'no thanks',
      created_at: null
    }
    
    const res = {
      data: {
        name: 'Garbo Hamburgler',
        age: 1337,
        sex: '0%',
        created_at: 133713371337
     } 
    }
    
    //fake DB call
    console.log(Object.assign({}, user, res.data))

我试图用扩散算子显示它,但我的REPL显然没有它,所以我放弃了。见这里:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

这也应该有效:

return {
  ...user,
  ...res.data
}

但是,你需要Babel:https://babeljs.io/docs/plugins/transform-object-rest-spread/

我更喜欢这两种方式,因为它是不可变的。你没有重新分配任何变量。您在分配后进行只读,然后在创建新对象时进行。

Object.assign()和点差运算符都有从右到左的优先级,因此“较新的也称为最右侧”的值将覆盖“较旧的又名左侧”值。

坚持下去:

const user = {
    name: null,
    age: null,
    sex: null,
    created_at: null
}

// if inside an async function
const updatedUserObj = await promise
  .get(/*url*/)
  .then(res => Object.assign({}, user, res.data))

console.log(updatedUserObj)

以下是一些向您展示Object.assign()的示例:

const user = {
    name: null,
    age: null,
    sex: null,
    created_at: null
}

const someObject = {
  coffee: {
    good: true,
    flavour: 'ultra',
    shouldDrink: true,
    age: 1337
  }
}

// Notice how coffee is the property on the object we just created:
console.log('FIRST EXAMPLE', JSON.stringify(Object.assign({}, someObject), null, 2))

// Notice how someObject is the property on the new object and coffee is its property
console.log('SECOND EXAMPLE', JSON.stringify(Object.assign({}, { someObject }), null, 2))

// Now, watch what happens if we begin overwriting:
console.log('THIRD EXAMPLE', JSON.stringify(Object.assign({}, user, someObject), null, 2))

console.log('FOURTH EXAMPLE', JSON.stringify(Object.assign({}, { user, someObject }), null, 2))

console.log('FIFTH EXAMPLE', JSON.stringify(Object.assign({}, user, { someObject }), null, 2))

console.log('SIXTH EXAMPLE', JSON.stringify(Object.assign({}, { user },  someObject), null, 2))

答案 1 :(得分:1)

选项3是更好的选择。在使用Object.assign()的示例中,您使用工厂函数来创建user的新实例。这样做的好处是,当您要创建新的user实例时,它不会强制您调用user的构造函数。您也可以使用Object.create()

这是Object Orientated Programming的基本示例。

请在此处阅读更多内容,以便更好地理解https://www.sitepoint.com/object-oriented-javascript-deep-dive-es6-classes/

相关问题