承诺链中承诺之间的延迟 [英] Delays between promises in promise chain

查看:24
本文介绍了承诺链中承诺之间的延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在使用以下代码连续运行几个 Promise:

Let's say I am using the following code to run a couple of promises in series:

let paramerterArr = ['a','b','c','d','e','f']
parameterArr.reduce(function(promise, item) {
  return promise.then(function(result) {
    return mySpecialFunction(item);
  })
}, Promise.resolve())

代码简单地调用 mySpecialFunction(它返回一个 promise),等待 promise 被解析,然后再次调用 mySpecialFunction 等等.因此该函数对数组中的每个元素都以正确的顺序调用一次.

The code simply calls mySpecialFunction (which returns a promise), waits for the promise to be resolved and then calls mySpecialFunction again etc. So the function is called once for every element in the array, in the correct order.

如何确保每次调用 mySpecialFunction(item) 之间至少有 50 毫秒的延迟?

How could I make sure that there is a delay of at least 50 milliseconds between every call of mySpecialFunction(item)?

promise 以正确的顺序执行很重要,mySpecialFunction 的执行时间每次都不同.

It is important that the promises are executed in the right order and the execution time of mySpecialFunction varies every time.

我猜同步睡眠会起作用,但我不打算在单独的线程中运行此代码,因此它会导致浏览器中烦人的 ui 冻结.

I guess a synchronous sleep would work, but I'm not planning to run this code in a separate thread, so it would cause annoying ui freezes in the browser.

我不确定 setTimer 是否可以用于此目的.我的意思是我不能推迟承诺的回报.

I'm not sure if setTimer could somehow be used for this. I mean I can't delay the returning of a promise.

推荐答案

答案是好的,但是他们等待的时间太长了,因为所有答案都在等待不管实际操作是否超过了已经 50 毫秒了.

The answers are good, but they wait too long since all the answers wait regardless of whether or not the actual operation took more than 50ms already.

你可以使用Promise.all.

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
let parameterArr = ['a','b','c','d','e','f'];
parameterArr.reduce(function(promise, item) {
  return promise.then(function(result) {
    return Promise.all([delay(50), myPromise(item)]);
  });
}, Promise.resolve());

这篇关于承诺链中承诺之间的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆