gpt4 book ai didi

javascript - 等待上一个异步函数完成

转载 作者:行者123 更新时间:2023-11-28 15:12:07 25 4
gpt4 key购买 nike

我在我的项目中添加了一个函数,该函数输出字符之间有超时的句子,效果很好。问题是 JS 异步执行所有函数调用,而我希望它等待上一句完成后再开始下一句。

我希望这是一个可链接的 jQuery 函数,最终可以与 .delay 一起使用。我有很多句子要打印,因此嵌套回调会很乏味。

我尝试了多种方法,但最接近的方法是在每个方法之间延迟调用该函数,当我必须计算函数完成时间时,这会变得非常烦人。

这是最新的

var printMsg = function(msg) {
var index = 0;
var out = $('#out').append('<pre></pre>');
var msgOut = setInterval(function() {
out.children(':last-child').append(msg[index++]);
if (index >= msg.length) {
clearInterval(msgOut);
};
}, 150);
}

然后我必须这样称呼他们

var timeout = 8000;
printMsg('Lorem ipsum Laboris Duis cupidatat ut id enim nisi');
setTimeout(function() {
printMsg('Lorem ipsum Laboris Duis cupidatat ut id enim nisi');
}, timeout);
timeout += 8000;
setTimeout(function() {
printMsg('Lorem ipsum Laboris Duis cupidatat ut id enim nisi');
}, timeout);

Fiddle

最佳答案

使用原生 ES6 Promise 和链接的工作示例:https://jsfiddle.net/5hro5zq1/

var printMsg = function(msg) {
var promise = new Promise(function(resolve, reject){
var index = 0;
var out = $('#out').append('<pre></pre>');
var msgOut = setInterval(function() {
out.children(':last-child').append(msg[index++]);
if (index >= msg.length) {
clearInterval(msgOut);
resolve();
};
}, 150);
});
return promise;
}

function printMessages(messages){
if(messages.length){
printMsg(messages[0])
.then(function(){
printMessages(messages.slice(1, messages.length))
});
}
}

var messages = [
'This is the first sentence.',
'This is another sentence.',
'We can do this all day long...'
];

printMessages(messages);

如果你想要这样的东西,你可能想要使用 jQuery Promise 或至少使用 polyfill:https://github.com/stefanpenner/es6-promise

关于javascript - 等待上一个异步函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35971825/

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