TypeScript/JavaScript中如何将async返回的Promise赋值给对象属性
问题原因与修正方案
你代码里存在3处语法和类型标注错误,修正后即可正常运行:
async关键字仅可用于修饰函数,不可修饰常量声明。你给async_item_A01、async_item_A02、parentItem三个常量前添加的async属于无效语法,需要移除,async需加在箭头函数定义前标记异步函数属性。- async函数的返回值会被自动包装为Promise类型,你给两个异步箭头函数标注的返回类型
ItemI存在错误,应修正为Promise<ItemI>。原类型标注会让TypeScript误判函数返回值为ItemI类型,和subItems要求的Promise<ItemI>[]类型不匹配,这就是你看到的报错的直接原因。 parentItem是普通对象,不需要用async修饰,直接按ItemI类型声明即可。
修正后的完整代码
// interface for each item object interface ItemI { id: number, name: string, subItems?: Promise<ItemI>[] } // item object 1 const item_A01: ItemI = { id: 1, name: 'item_A01' } // item object 2 const item_A02: ItemI = { id: 2, name: 'item_A02' } // async function returns Promise of item object const async_item_A01 = async (): Promise<ItemI> => { return item_A01 }; const async_item_A02 = async (): Promise<ItemI> => { return item_A02 }; // parent item with the Promised item objects const parentItem: ItemI = { id: 0, name: 'parentItem', subItems: [async_item_A01(), async_item_A02() ] } // function to work with an actual item // from the Promised / async constants // by the provided index async function getItem (itemIndex: number) { if (!parentItem.subItems) return const resolved_item: ItemI = await parentItem.subItems[itemIndex]; console.log('my resolved item is:', resolved_item.name); }
修正后调用getItem(0)即可正常输出item_A01,符合你预期的惰性取数逻辑。
内容的提问来源于stack exchange,提问作者Felix
相关产品推荐
相关产品推荐

