首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将一个Fetch函数的API响应时间传递给另一个异步函数?

如何将一个Fetch函数的API响应时间传递给另一个异步函数?
EN

Stack Overflow用户
提问于 2021-05-27 12:35:27
回答 1查看 79关注 0票数 0

我可以在'makeAPICall‘函数中获得接口响应时间(持续时间)。现在我需要将它( duration变量的值)传递给另一个异步函数。我想知道您是否可以提供解决方案?

代码语言:javascript
运行
复制
const makeApiCall = ClientFunction(() => {
  console.time("timer1");
  const testLocation = () => fetch('https://xxxxxx',
    {method : 'GET',
      headers:{
        hash: 'xxxxx',
        id: 'xxxxxxxxc'
      }
    })
    .then(response => response.json())
    .then(data => {
      let duration = console.timeEnd("timer1");
      console.log(duration);
    });
  return testLocation();
});



test('test', async t => {
  await makeApiCall();
  console.log(duration)?????
});
EN

回答 1

Stack Overflow用户

发布于 2021-05-27 13:56:04

第一个问题:console.timeEnd没有返回任何东西,它将ellapsed时间打印到控制台。请改用performance.now()或仅使用Date

2)然后返回上一次then的持续时间。

代码语言:javascript
运行
复制
const makeApiCall = ClientFunction(() => {
  const start = new Date().getTime();
  const testLocation = () => fetch('https://xxxxxx',
    {method : 'GET',
      headers:{
        hash: 'xxxxx',
        id: 'xxxxxxxxc'
      }
    })
    .then(response => response.json())
    .then(data => {
       const end = new Date().getTime();
       return end - start;
    });
  return testLocation();  // This returns a Promise<number>
});



test('test', async t => {
  const duration = await makeApiCall();
  console.log(duration)?????
});
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67715737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档