When or who does pass resolve and reject functions to JS promises?

后端 未结 5 1612
无人共我
无人共我 2021-01-12 11:52

I have begin learning javascript promises. But I just can\'t understand the concept of promises. The thing that bothers me most is who is passing the Resolver and Reject fun

5条回答
  •  迷失自我
    2021-01-12 12:22

    The Promise constructor is initialized with a callback, and the constructor passes reject and resolve as parameters when the callback is called.

    Here is a simple demo:

    class PromiseDemo {
      constructor(cb) {
        cb(this.resolve.bind(this), this.reject.bind(this));
      }
      
      resolve(d) {
        console.log('resolve', d);
      }
      
      reject(d) {
        console.log('reject', d);
      }
    }
    
    new PromiseDemo((resolve, reject) => {
      Math.random() > 0.5 ? resolve('1') : reject('1');
    });

提交回复
热议问题