Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
327 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...