我正在尝试在我的代码中实现 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);
}
}
}
最佳答案
使用一组 Promise,其中每个resolve() 都在 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')
});
}
关于javascript - setTimeout 函数完成后调用 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53354887/