[英]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
计时器的问题关闭。)
drawChart(data)
. 单击开始按钮时-使用预定义的函数开始绘制点: drawChart(data)
。 The points should be added every second. 这些点应该每秒添加一次。 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);
};
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.