javascript - setTimeout 函数完成时调用 Promise
问题描述
我正在尝试在我的代码中实现 Promise 语句,并希望得到一些帮助。我有一个使用 setTimeout 运行的函数。我想在完成后调用一个函数。
尝试包括 Promise 语句,但我觉得我做的不正确。任何反馈都是有帮助的
function App(){
let exampleProm = new Promise(
function(){
type.type("hello , dexter", 100);
}
).then(console.log('finished'));
}
App();
//首先被调用的代码
module.exports = {
type: function(phrase, delaySpeed){
let total = 0;
let empty = [];
for(let i = 0; i < phrase.length;i++){
total += delaySpeed;
setTimeout(() => {
empty.push(phrase.charAt(i));
process.stdout.write(chalk.blue.bold(empty[i]));
if(empty.length === phrase.length){ //if complete
process.stdout.write('\n'); //puts on separate line
}
},total);
}
}
}
解决方案
使用每个 resolve() 内部的 promise 数组,setTimeout()
然后Promise.all()
在它们全部解析后运行代码
module.exports = {
type: function(phrase, delaySpeed) {
let total = 0;
let empty = [];
let promises = []
for (let i = 0; i < phrase.length; i++) {
total += delaySpeed;
// new promise for each character
let promise = new Promise(function(resolve, reject) {
setTimeout(() => {
empty.push(phrase.charAt(i));
process.stdout.write(chalk.blue.bold(empty[i]));
if (empty.length === phrase.length) { //if complete
process.stdout.write('\n'); //puts on separate line
}
// assuming above writes are synchronous can now resolve promise
resolve()
}, total);
});
// push new promise to array
promises.push(promise)
}
// return the all() promise
return Promise.all(promises)// add another then() if you need to return something to next then() in App()
}
}
function App(){
type.type("hello , dexter", 100).then(function(){
// this then() fires when the Promise.all() resolves
console.log('finished')
});
}
推荐阅读
- excel - 尝试让 Google 地图计算距离时出现运行时错误 91
- mysql - 如何比较同一张表中的两列,并获得不同的一列
- python - 使用多个 dask 块时,xr.DataArray.where 将有效点设置为 nan
- mongodb - 如何从 dockerfile 启动 mongodb
- java - 如何在android应用程序中显示缺货项目
- azure-webjobs - 如何在 IEventProcessor.ProcessEvents 方法中处理失败消息
- powershell - 从两个对象构造自定义对象
- spring-boot - 服务器发送事件 - 几次断开连接后流未重新连接
- javascript - 如何正确定义函数的数组参数?
- python - 不理解地计算总和