我很难使用 async/await 使其在循环中同步工作。我的小 showChart 所做的是从服务器请求 10 个项目并使用 plotly 在服务器上绘制它。为了让它像每秒一样,我喜欢把一些睡眠时间最好精确到 1000 毫秒。然而,console.log 似乎每秒打印一次,但 drawChart 函数不是每秒调用一次,而是在最后一分钟显示所有内容。我怎样才能让它每秒画一次?先谢谢了~~!!
/**
* data comes with { status: '' , message:{ result : [{point:''}, {point:''} ...]}} in json format.
**/
async function showChart(url, nextPage ){
let requestUrl = url+nextPage;
let resposne = await fetch(requestUrl);
let data = await resposne.json();
data = data.message.result;
let points = await data.map(e=>e.point);
console.log(fp1Deltas);
const num = fp1Deltas.map( async delta =>{
delay(1000);
// await sleep (1000);
drawChart(delta);
console.log( delta);
});
console.log('done');
}
const sleep = ms=>{
return new Promise(resolve => setTimeout(resolve, ms));
}
const delay = ( ms) => {
var start = new Date().getTime();
var end = start;
while( end < start + ms ){
end = new Date().getTime();
}
};
const drawChart = point =>{
Plotly.extendTraces('chart1', {
y: [
[point]
]
}, [0]);
}
$(document).ready(function () {
Plotly.plot('chart1', [{
y: [],
type: 'line'
}]);
showChart(requestLocation, page);
// fetchData(requestLocation,page);
}); // end of document ready
Helenr
相关分类