我写
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的值了,请大神解惑原因
请大神解惑原因
不加大括号,就相当于return 。get: () =>{ return new Promise } 等同于get: () => new Promise。你第二种get函数相当于没有返回promise