gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:28:46 29 4
gpt4 key购买 nike

所以我有这个对象:

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

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

所以 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);

哪种方法最好/正确?一个比另一个有什么优势? 我目前正在使用第三个选项。任何帮助将不胜感激。

最佳答案

我喜欢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))

关于javascript - 如何在 promise 中正确设置对象值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47048344/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com