Search code examples
javascriptpromisees6-promise

Why promis only works in the last variable?


Why "then" in var test1 not show 1111111? But if just use resolve(); work fine. What wrong? How to do multiple promise requests at the same time?

window.testFunc = function() {

  let _self = this;

  this.test = function() {
    _self.resolve();
  };

  return new Promise(function(resolve, reject) {

    _self.resolve = resolve;
    _self.reject = reject;

    //this work fine
    //resolve();

    //this not work
    setTimeout(function() {
      _self.test();
    }, 300);
  });

};


let test1 = window.testFunc();
let test2 = window.testFunc();

test1.then(function(value) {
  console.log(111111);
});
test2.then(function(value) {
  console.log(222222);
});


Solution

  • this has the same value each time you call window.testFunc, so _self.test is the same property (which gets overwritten each time).

    Use a local variable with a new object (let _self = {};) instead of a shared object.

    window.testFunc = function() {
    
        let _self = {};
    
        _self.test = function () {
            _self.resolve();
        };
    
        return new Promise(function (resolve, reject) {
    
            _self.resolve = resolve;
            _self.reject = reject;
    
            //this work fine
            //resolve();
    
            //this not work
            setTimeout(function(){
                _self.test();
            }, 300);
        });
    
    };
    
    
    let test1 = window.testFunc();
    let test2 = window.testFunc();
    
    test1.then(function(value){
        console.log(111111);
    });
    test2.then(function(value){
        console.log(222222);
    });