在一个项目中,我调用了具有 setTimeout 的多个函数。在下面的代码中,我似乎无法让我的代码按顺序运行。例如,调用一个函数,然后调用下一个函数,然后调用下一个函数。每个人都在等待另一个人完成。
随意更改我的代码,因为我很想了解有关此事的更多信息。
**更新
由于很难解释我的问题,我想我会发布完整的代码。在问候页面中,我使用inquirerJS 向用户提示一个问题。当我询问用户时,我的第三个函数会启动,而无需等待承诺解决。
TYPE PAGE
module.exports = {
writer: 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()
}
}
GREET PAGE
const inquirer = require('inquirer');
let intro = require('./type.js');
let chalk = require('chalk');
let type = require('./type.js');
let greet = function(){
let questions = [{
type: 'input',
name: 'firstName',
message: 'what your name',
}];
inquirer
.prompt(questions)
.then(answers => {
setTimeout(function(){
type.writer(`Hello ${answers.firstName}`,100);
},500);
}
)
}
module.exports = greet;
MAIN APP PAGE
let initialGreeting = require('./user.js');
function App(){
function second(){
return new Promise(function(resolve,reject){
setTimeout(function a(){
initialGreeting();
resolve();
}, 200);
}
)
function third(){
console.log('finished')
}
type.writer('abc',100).then(second).then(third);
};
App();