2 回答
TA贡献2065条经验 获得超14个赞
如果我明白您的意思,则可以通过将触发器中的代码包装在setTimeout(超时值为0)中,然后包装在新的Promise中来实现
使用async / await就像
$('#trigger').click(async (e) => {
for (let chart of Highcharts.charts) {
await new Promise(resolve => setTimeout(() => {
chart.series.forEach(series => series.setVisible(undefined, false));
chart.redraw();
resolve();
}, 0));
}
});
TA贡献1868条经验 获得超4个赞
一般解决方案
通常,如果您要在循环中顺序地链接promise,可以使用以下格式
function promiseChain(i) {
return new Promise(resolve => {
/* DO ASYNC STUFF */
// Resolve with some result if the next item in the chain needs it
return resolve("OK");
});
}
let p = Promise.resolve(null);
for (let i = 0; i < 5; i++) {
p = p.then(prevResult => {
if (prevResult) {
// Do stuff with prevResult if needed
}
// Chain next item
return promiseChain(i);
});
}
日志示例
这将记录0-4,一次记录一次,每次间隔等待一秒钟。
function promiseChain(i) {
return new Promise(resolve => {
setTimeout(() => {
console.log(i);
return resolve("OK");
}, 1000)
});
}
let p = Promise.resolve(null);
for (let i = 0; i < 5; i++) {
p = p.then(prevResult => {
if (prevResult) {
// Do stuff with prevResult if needed
}
return promiseChain(i);
});
}
添加回答
举报