简体   繁体   English

在 promise 内的 setTimeout 之后解析 promise

[英]resolve promise after setTimeout inside promise

I would like to resolve my promise after my setTimeout will be finished.我想在我的 setTimeout 完成后解决我的 promise。 I have a few functions like step The main idea is to get step results sequentially.我有几个函数,比如step主要思想是按顺序获取 step 结果。 PS we can't mutate setTimeout. PS我们不能改变setTimeout。

function step (done) {
  return new Promise((resolve, reject) => {
    try {
      setTimeout(done, 5100, 'hello world')
      resolve()
    } catch (error) {
      reject()
    }
  })
}

If you can't mutate the setTimeout remove it.如果您不能改变setTimeout ,请将其删除。 Instead of putting the setTimeout in the step function create a new delay function that returns a promise.不要将setTimeout放在步骤 function 中,而是创建一个返回 promise 的新delay function。 You can then use async/await to walk through the steps after certain delays.然后,您可以在某些延迟后使用async/await来完成这些步骤。

 function delay(time = 1000) { return new Promise(res => { setTimeout(() => res(), time); }); } function step(fn, n) { fn(`hello world ${n}`); } const fn = (str) => console.log(str); async function main() { step(fn, 1); await delay(5000); step(fn, 2); await delay(3000); step(fn, 3); } main();

If you can change the done function, you can do like below.如果您可以更改已done的 function,您可以执行以下操作。

 function step(done) { return new Promise((resolve, reject) => { immutableFunc(done(resolve, reject)); }); } function immutableFunc(done) { setTimeout(done, 1000, "hello world"); } function done(resolve, reject) { return arg => { try { console.log(arg); resolve(); } catch (error) { reject(error); } }; } async function test() { try { await step(done); await step(done); await step(done); } catch (err) { console.log(err); } } test();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM