简体   繁体   English

Javascript等待Promises返回数据,然后分配onClick事件侦听器对返回的数据执行操作

[英]Javascript wait for Promises to return data then assign onClick event listener to perform action on returned data

(UPDATE: I'm now able to solve the issue with plotting the data by using async / await to wait for the promise to resolve... However, now I'm facing the issue with how to stop the setInterval timer that's in a closure.) (更新:我现在可以通过使用async / await来等待对诺言的解析来绘制数据,从而解决该问题。但是,现在,我面临着如何停止a中的setInterval计时器的问题关闭。)

I want to accomplish the following: 我要完成以下任务:

  • Send 10 fetch requests sequentially and measure response time for each request (in millisec) 顺序发送10个提取请求,并测量每个请求的响应时间(以毫秒为单位)
  • For each request push response time to an array 对于每个请求,将响应时间推送到数组
  • On click of a start button - starts the plotting of points with a predefined function: drawChart(data) . 单击开始按钮时-使用预定义的函数开始绘制点: drawChart(data) The points should be added every second. 这些点应该每秒添加一次。
  • On click of a stop button - stop the plotting. 单击停止按钮时-停止绘图。

onLoad event listener: onLoad事件侦听器:

window.onload = async function () {
   drawChart([]);
   const data = await fetchData(15);
   document.getElementById("start").onclick = () => plotData(data);

   // I want to be able to clearInterval on click of Stop button... but its not working...
   document.getElementById("stop").onclick = clearInterval(plotData);  
};

plot / fetch function: 绘图/获取功能:

const plotData = (data) => {
  let i = 0;
  // How do i clear this interval outside of this function?
  const interval = setInterval( () => {
    i++;
    if (i === data.length) { clearInterval(interval); }
    let newData = data.slice(0,i);
    drawChart(newData); 
    console.log('draw');
  }, 1000);
}

const fetchData = async (times) => {
  let url = `https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-1295/lounging-dog.jpg`;
  const data = [];
  for (let i = 0; i < times; i++) {
    start = (new Date()).getTime();
    await fetch(url)
      .then( res => {
        end = (new Date()).getTime();
        console.log('times', i+1);
        console.log('response milisec', end - start);            
        data.push({ xVal: i+1, yVal: end-start}); 
      })
      .catch( e => console.log(e));   
  }
  return data;
};

What I can't wrap my mind about is how to clearInterval in the window context when the setInterval is defined within a callback. 我无法确定的是,当在回调中定义setInterval时,如何在窗口上下文中清除clearInterval。

You can also see my CodePen for more information. 您也可以查看我的CodePen以获取更多信息。

Thanks in advance! 提前致谢!

To wait for a promise to resolve use await 要等待诺言解决,请使用await

// get fetch call data
const data = await fetchData(10).then( (res) => {
  console.log(res);
});

// assign button onClick handler, data undefined
document.getElementById("start").onclick = drawChart(data);  

A better way to do this is, instead of waiting for each promise in fetchData to resolve before starting the next fetch, is to create each promise and then await all of them. 一种更好的方法是,创建每个承诺,然后等待所有承诺,而不是等待fetchData每个承诺解决之后再开始下一个提取。 It would look something like this: 它看起来像这样:

 const fetchData = async (times) => { const url = 'https://reqres.in/api/users?page=2' const promises = []; for (let i = 0; i < times; i++) { start = (new Date()).getTime(); promises.push( fetch(url) .then( res => { end = (new Date()).getTime(); console.log('times', i+1); console.log('response milisec', end - start); return { xVal: i+1, yVal: end-start}; }) .catch( e => console.log(e)) ); } let data = await Promise.all(promises); console.log(data) return data; }; fetchData(3); 

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

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