ES6承诺超时间隔 [英] ES6 promises with timeout interval

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

问题描述

我正在尝试将我的一些代码转换为Promise,但是我不知道如何在Promise中链接一个新的Promise.

I'm trying to convert some of my code to promises, but I can't figure out how to chain a new promise inside a promise.

我的promise函数应该每秒钟左右检查一次数组的内容,并且如果其中有任何项应该解析.否则,应等待1秒钟,然后再次检查,依此类推.

My promise function should check the content of an array every second or so, and if there is any item inside it should resolve. Otherwise it should wait 1s and check again and so on.

function get(){
    return new Promise((resolve) => {

      if(c.length > 0){
        resolve(c.shift());

      }else{
        setTimeout(get.bind(this), 1000);
      }

    });

}


let c = [];

setTimeout(function(){
  c.push('test');
}, 2000);

这就是我期望get()承诺函数起作用的方式,它应该在最多2或3秒后打印测试":

This is how I expect my get() promise function to work, it should print "test" after 2 or 3 seconds max:

get().then((value) => {
  console.log(value);
});

很明显它不起作用,什么也没印刷

Obviously it doesn't work, nothing is ever printed

推荐答案

setTimeout本身具有可怕的链接和错误处理特征,因此始终

setTimeout has terrible chaining and error-handling characteristics on its own, so always wrap it:

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function get(c) {
  if (c.length) {
    return Promise.resolve(c.shift());
  }
  return wait(1000).then(() => get(c)); // try again
}

let c = [];
get(c).then(val => console.log(val));
wait(2000).then(() => c.push('test'));

虽然您没有要求,但为了他人的利益,这是async/await发光的一个很好的例子:

While you didn't ask, for the benefit of others, this is a great case where async/await shines:

const wait = ms => new Promise(r => setTimeout(r, ms));

async function get(c) {
  while (!c.length) {
    await wait(1000);
  }
  return c.shift();
}

let c = [];
get(c).then(val => console.log(val));
wait(2000).then(() => c.push('test'));

请注意,由于async函数是隐式执行此操作的,因此这次我们不需要Promise.resolve().

Note how we didn't need Promise.resolve() this time, since async functions do this implicitly.

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

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