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

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

问题描述

假设我使用以下代码来串行执行几个承诺:

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

代码简单地调用mySpecialFunction(它返回一个承诺),等待承诺解决,然后再次调用mySpecialFunction等等。因此该函数对于数组中的每个元素都被调用一次,正确



我如何确保每次调用 mySpecialFunction(item)



重要的是,承诺以正确的顺序执行,执行时间 mySpecialFunction 每次都会有所不同。



我想同步睡眠可以工作,但是我不打算在单独的线程中运行此代码,所以这会在浏览器中导致烦人的ui冻结。



我不知道setTimer是否可以以某种方式用于此。我的意思是我不能拖延承诺的回归。

解决方案

答案是好的,但是他们等待太久,因为所有答案都等待或者不是实际操作已经超过了50ms。



您可以使用 Promise.all p>

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


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())

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.

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

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

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.

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

解决方案

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.

You can use Promise.all for it.

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

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

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