创建一个硬编码的Promise<T>[],以返回组件,因为还没有后端。

huangapple go评论65阅读模式
英文:

Create a hardcoded Promise<T>[] to return component as there is no backend yet

问题

我有一个函数,将来会进行后端调用以获取数据。现在我想向组件返回虚拟数据。如何创建硬编码的 Promise&lt;IMySetting&gt;[]

export function getMySettings(id: number): Promise&lt;IMySetting&gt;[] {
    
    const settings = (
    ): IMySettings =&gt; {
        return {
            name: &#39;test&#39;
        };
    };
    const myArray = [setting, setting];
    return ... //如何创建一个 Promise&lt;IMySetting&gt; 数组
}
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&lt;IMySetting&gt;[]

export function getMySettings(id: number): Promise&lt;IMySetting&gt;[] {
    
    const settings = (
    ): IMySettings =&gt; {
        return {
            name: &#39;test&#39;
        };
    };
const myArray = [setting, setting];
  return ... //How to create an array of Promise&lt;IMySetting&gt;
}
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&lt;IMySetting[]&gt; {   
  return [
    { name: &#39;test1&#39; },
    { name: &#39;test2&#39; }
  ];
}

See Playground


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&lt;IMySetting&gt;[] {   
  return [
    Promise.resolve({ name: &#39;test1&#39; }),
    Promise.resolve({ name: &#39;test2&#39; })
  ];
}

See Playground

huangapple
  • 本文由 发表于 2023年7月11日 12:35:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76658741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定