React中promise异步使用的大括号问题,加和不加有2种不同的效果,请问原理是什么?
我写
const blankRef = await currentBlank.current.get()
get函数的两种写法竟然有不同的效果,请问这两者的区别在哪里?第一种正确的写法
const getData = async () => {
const BrandItemRef = await currentBrandItem.current.get()
const CategoryItemRef = await currentCategoryItem.current.get()
const ProductlineItemRef = await currentProductlineItem.current.get()
const StyleItemRef = await currentStyleItem.current.get()
const HandcountItemRef = await currentHandcountItem.current.get()
return {
BrandItemRef,
CategoryItemRef,
ProductlineItemRef,
StyleItemRef,
HandcountItemRef,
}
}
useEffect(() => {
currentRef.current = {
get: () =>
new Promise((resolve: any) => {
getData().then((res) => {
if (
res.BrandItemRef.state &&
res.CategoryItemRef.state &&
res.ProductlineItemRef.state &&
res.StyleItemRef.state &&
res.HandcountItemRef.state
) {
console.log(res)
resolve({
state: true,
name: 'blank',
data: {
BrandItem: res.BrandItemRef.data,
CategoryItem: res.CategoryItemRef.data,
ProductlineItem: res.ProductlineItemRef.data,
StyleItem: res.StyleItemRef.data,
HandcountItem: res.HandcountItemRef.data,
},
}).catch((error) => {
if (error && error.errorFields) {
}
})
}
})
}),
}
}, [])
第二种错误的写法
const getData = async () => {
const BrandItemRef = await currentBrandItem.current.get()
const CategoryItemRef = await currentCategoryItem.current.get()
const ProductlineItemRef = await currentProductlineItem.current.get()
const StyleItemRef = await currentStyleItem.current.get()
const HandcountItemRef = await currentHandcountItem.current.get()
return {
BrandItemRef,
CategoryItemRef,
ProductlineItemRef,
StyleItemRef,
HandcountItemRef,
}
}
useEffect(() => {
currentRef.current = {
get: () =>{
new Promise((resolve: any) => {
getData().then((res) => {
if (
res.BrandItemRef.state &&
res.CategoryItemRef.state &&
res.ProductlineItemRef.state &&
res.StyleItemRef.state &&
res.HandcountItemRef.state
) {
console.log(res)
resolve({
state: true,
name: 'blank',
data: {
BrandItem: res.BrandItemRef.data,
CategoryItem: res.CategoryItemRef.data,
ProductlineItem: res.ProductlineItemRef.data,
StyleItem: res.StyleItemRef.data,
HandcountItem: res.HandcountItemRef.data,
},
}).catch((error) => {
if (error && error.errorFields) {
}
})
}
})
})
}
}
}, [])
区别在于get: () => 是直接new Promise还是加个函数大括号,如果加了大括号,无法获取resolve的值了,请大神解惑原因
请大神解惑原因
回复
1个回答
test
2024-06-19
不加大括号,就相当于return 。get: () =>{ return new Promise } 等同于get: () => new Promise。你第二种get函数相当于没有返回promise
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容