如何解决使用promise运行下一个功能不起作用-PLAIN JAVASCRIPT
我是Java开发的新手。
项目- 我目前正在使用网络聊天机器人应用程序。
问题- 我无法使用promise()函数一个接一个地运行多个函数。
代码-
var messages = [
`Hello name`,`I'm hosting a party on Sunday at my house,for my birthday`,`I'll be really happy if you'd come`,];
chatwindow = document.querySelector(".message-day");
const startChat = () => {
return new Promise(function (resolve,reject) {
messages.forEach((message) => {
setTimeout(() => {
chatwindow.innerHTML += `
<div class="message">
<div class="message-wrapper">
<div class="message-content">
<h6 class="text-dark">Karan</h6>
<span>${message}</span>
</div>
</div>
<div class="message-options">
<div class="avatar avatar-sm"><img alt="" src="./assets/media/avatar/6.png"></div>
<span class="message-date">9:12am</span>
</div>
</div> `;
},2000);
});
resolve();
});
};
startChat().then(() => {
console.log("2nd Functions");
});
You can also see the code live here
在 startchat() [第一个功能]结束后,如何运行第二个功能。
解决方法
现在,您为3个操作返回1个诺言,但您似乎要使所有3个操作都异步。为此,您需要为每个异步操作返回一个Promise。
您可能正在寻找这样的东西:
const messages = [
`Hello name`,`I'm hosting a party on Sunday at my house,for my birthday`,`I'll be really happy if you'd come`,];
const chatWindow = document.querySelector(".message-day");
const startChat = () => messages.map(
// Returns array of promises wrapping
// each message into a promise
(message,index) => new Promise(resolve => {
setTimeout(() => {
chatWindow.innerHTML += `
<div class="message">
<div class="message-wrapper">
<div class="message-content">
<h6 class="text-dark">Karan</h6>
<span>${message}</span>
</div>
</div>
<div class="message-options">
<div class="avatar avatar-sm"><img alt="" src="./assets/media/avatar/6.png"></div>
<span class="message-date">9:12am</span>
</div>
</div>`;
resolve(message);
},2000 * index);
})
);
Promise.all(startChat())
.then(args => {
// args will contain same strings as messages
console.log("2nd Functions",args);
});
如果您想在打印每条消息之前/之后调用回调,我建议将回调作为参数传递给startChat
并在需要时调用它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。