Search code examples
javascriptecmascript-6es6-promise

Avoid a promise to execute when created


I do not want a promise to run before it is actually called by the script, but unfortunately a promise by default runs the moment it's created.

Is there a way to avoid this default execution of the code when the promise is created?


Solution

  • You can put it in a function that returns the promise, then call the promise later.

    Set up your function which returns a promise:

    function myAsyncFunction(url) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.onload = () => resolve(xhr.reponse);
        xhr.onerror = () => reject(xhr.statusText);
        xhr.send();
        //  Or whatever you want in your function
      });
    }
    

    Then later, call your function:

     myAsyncFunction(url)
       .then( ... ) 
       .then( ... ) 
       .catch( ... )