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

查看:27
本文介绍了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函数应该每隔一秒左右检查一次数组的内容,如果里面有任何项目应该解决.否则它应该等待 1s 并再次检查等等.

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'));

注意我们这次不需要 Promise.resolve(),因为 async 函数隐式地做到了这一点.

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

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

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