简体   繁体   English

函数返回已解决的承诺而不是数据

[英]Function returns resolved promise instead of data

I have this function:我有这个功能:

const buildDataSource = (): Promise<Data> => {
  const data = fetch('https://jsonplaceholder.typicode.com/posts')
    .then((response) => response.json())
    .then((items) => items.map((item: RawDataItem, idx: number) => ({
      key: idx,
      randStr: item.title.substring(1, 24),
    })));
  return data;
};

And call it with this: const data = buildDataSource();并用这个调用它: const data = buildDataSource();

but data is a resolved promise that includes the data, not the data itself.data是一个已解决的承诺,包括数据,而不是数据本身。 Where am I going wrong here?我哪里出错了?

Problem with promises and async in general is that once you start with it you need to put it everywhere up your stack. Promise 和 async 的一般问题在于,一旦开始使用它,就需要将它放在堆栈中的任何地方。 Basically the function that is consuming your buildDataSource will also have to be async and so on ...基本上,消耗你的 buildDataSource 的函数也必须是异步的等等......

On a different note you should definatelly look async/await because it makes reading async code much easier (your buildDataSource as async):换个角度看,你肯定应该看异步/等待,因为它使阅读异步代码变得更加容易(你的 buildDataSource 为异步):

const buildDataSource = async (): Promise<Data> => {
  const response= await fetch('https://jsonplaceholder.typicode.com/posts');
  const items = await response.json();
  const data = items.map((item: RawDataItem, idx: number) => ({
      key: idx,
      randStr: item.title.substring(1, 24),
    }));
  return data;
}

And then use it like this:然后像这样使用它:

const something = async () => {
   const data = await buildDataSource (); // data here is your list
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM