gpt4 book ai didi

javascript - NodeJS - setTimeout 完成后运行函数

转载 作者:行者123 更新时间:2023-12-03 00:42:50 25 4
gpt4 key购买 nike

正在开发一个项目,我在其中调用多个具有 setTimeout 功能的函数。在下面的代码中,我似乎无法让我的代码按顺序运行。例如,调用一个函数,然后调用下一个函数,然后调用下一个函数。每个人都在等待对方完成。

请随意更改我的代码,因为我很想了解有关此事的更多信息。

**更新

由于很难解释我的问题,我想我只会发布完整的代码。在欢迎页面中,我使用询问器 JS 向用户提示一个问题。当我询问用户时,我的第三个函数会启动,而不等待 promise 解决。

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();

最佳答案

返回你新的 promise :

let greet = function(){
let questions = [{
type: 'input',
name: 'firstName',
message: 'what your name',
}];
inquirer
.prompt(questions)
.then(answers => {
return new Promise(function(resolve,reject) {
setTimeout(function(){
type.writer(`Hello ${answers.firstName}`,100);
resolve();
},500);
}).then(function(){
console.log("run after")
});

}
)
}
module.exports = greet;

关于javascript - NodeJS - setTimeout 完成后运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53368420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com