JavaScript Promise,所有的。然后同时执行

发布于 2025-02-03 15:19:49 字数 690 浏览 1 评论 0原文

目前,所有的console.log遵循。然后同时执行。 我想要每个。然后等待前一个,我该怎么做?

function doIt(sentence) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(console.log(sentence))
        }, 2000)
    })
}

doIt('Place order')
    .then(() => setTimeout(() => { console.log('Cut the fruit') }, 2000))
    .then(() => setTimeout(() => { console.log('Add water and ice') }, 2000))
    .then(() => setTimeout(() => { console.log('Start the machine') }, 2000))
    .then(() => setTimeout(() => { console.log('Select topping') }, 2000))
    .then(() => setTimeout(() => { console.log('Serve the ice cream') }, 2000))

At the moment all the console.log following the .then, execute at the same time.
I want every .then to wait for the previous one, how can I do it?

function doIt(sentence) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(console.log(sentence))
        }, 2000)
    })
}

doIt('Place order')
    .then(() => setTimeout(() => { console.log('Cut the fruit') }, 2000))
    .then(() => setTimeout(() => { console.log('Add water and ice') }, 2000))
    .then(() => setTimeout(() => { console.log('Start the machine') }, 2000))
    .then(() => setTimeout(() => { console.log('Select topping') }, 2000))
    .then(() => setTimeout(() => { console.log('Serve the ice cream') }, 2000))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

说不完的你爱 2025-02-10 15:19:49

您必须建立一个前景链。

function doIt(sentence) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(console.log(sentence)), 2000);
  });
}

doIt("Place order")
  .then(() => doIt("Cut the fruit"))
  .then(() => doIt("Add water and ice"))
  .then(() => doIt("Start the machine"))
  .then(() => doIt("Select topping"))
  .then(() => doIt("Serve the ice cream"));

You have to create a promise chain.

function doIt(sentence) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(console.log(sentence)), 2000);
  });
}

doIt("Place order")
  .then(() => doIt("Cut the fruit"))
  .then(() => doIt("Add water and ice"))
  .then(() => doIt("Start the machine"))
  .then(() => doIt("Select topping"))
  .then(() => doIt("Serve the ice cream"));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文