Search code examples
javascriptpromise

How to import a Promise but not execute it immediately?


I am trying to create a modules which is returning a Promise, and here is my test code.

I have a test promise module:

const test = new Promise((resolve,reject)=>{
console.log('loaded promise test');
resolve(true);
});

export default test;

And I import it to my index:

import test from "./test.js";

console.log('end');

Then I have a result like this:

loaded promise test
end

What I actually want is to execute the promise where I need rather than at the very beginning.
Or maybe I can just import a prototype of the promise and new it when I want it, how can I do that?


Solution

  • i remember using that when i created a repository for database operations i used a functions that has a promise inside it

    the Promise is immediately invoked when it is created, so that's why i have wrapped it with a function, because it doesn't invoke immediately until you call it your self

    remember to make the function returns the promise as well like below:

    const test = () => {
      return new Promise((resolve,reject)=>{
        console.log('loaded promise test');
        resolve(true);
      });
    }
    
    export default test;
    
    // other file
    import {test} from 'test-file-path'
    
    // to invoke test you have to use it like that
    
    test()
    
    //also use it with await because it is asynchronous code like that
    
    await test()

    also you can use try catch block inside it for catch error and reject it

    const test = () => {
      return new Promise((resolve,reject)=>{
        try{
          console.log('loaded promise test');
          resolve(true);
        }catch(error){
          reject(error.message)
        }
      });
    }