英文:
Create a hardcoded Promise<T>[] to return component as there is no backend yet
问题
我有一个函数,将来会进行后端调用以获取数据。现在我想向组件返回虚拟数据。如何创建硬编码的 Promise<IMySetting>[]
export function getMySettings(id: number): Promise<IMySetting>[] {
const settings = (
): IMySettings => {
return {
name: 'test'
};
};
const myArray = [setting, setting];
return ... //如何创建一个 Promise<IMySetting> 数组
}
export interface IMySetting {
name: string;
}
英文:
I have a function which in future will make a backend call to get data. For now I want to return dummy data to component. How can create a hardcoded Promise<IMySetting>[]
export function getMySettings(id: number): Promise<IMySetting>[] {
const settings = (
): IMySettings => {
return {
name: 'test'
};
};
const myArray = [setting, setting];
return ... //How to create an array of Promise<IMySetting>
}
export interface IMySetting {
name: string;
}
答案1
得分: 2
只需将您的函数设置为 async
,然后您可以 return
您喜欢的任何内容,它将隐式解析为一个 Promise。
export interface IMySetting {
name: string;
}
async function getMySettings(id: number): Promise<IMySetting[]> {
return [
{ name: 'test1' },
{ name: 'test2' }
];
}
如果您真的出于某种原因想要一个 promise 数组,而不是一个解析为数组的 promise,您可以使用 Promise.resolve(value)
来创建一个已经解析的 promise。
export interface IMySetting {
name: string;
}
function getMySettings(id: number): Promise<IMySetting>[] {
return [
Promise.resolve({ name: 'test1' }),
Promise.resolve({ name: 'test2' })
];
}
英文:
Just make your function async
, and then you can return
whatever you like which will implicitly resolve to a Promise for you.
export interface IMySetting {
name: string;
}
async function getMySettings(id: number): Promise<IMySetting[]> {
return [
{ name: 'test1' },
{ name: 'test2' }
];
}
And if you really wanted an an array of promises for some reason, instead of a promise that resolves to an array, you can use Promise.resolve(value)
to create a promise that is already resolved.
export interface IMySetting {
name: string;
}
function getMySettings(id: number): Promise<IMySetting>[] {
return [
Promise.resolve({ name: 'test1' }),
Promise.resolve({ name: 'test2' })
];
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论