Let's say we have a promise:

const aPromise = new Promise(()=>{console.log('promise executed');}) 

Simply assigning this Promise, executes it and this shows on the console:

promise executed

And when I call the aPromise, it doesn't log on the console, and outcome of console.log(aPromise) shows that it is resolved.

My question is that how can I assign a Promise without it getting executed/resolved, so I can call it multiple times?

3 Answers

1
Shubh Dixit On Best Solutions

You can simply return a promise from function and assign it to variable

function returnpromise(val) {
  return new Promise((resolve, reject) => {
    if (val > 5) {
      resolve("resolved hello"); // fulfilled
    }
    else {
      reject("rejected"); // rejected
    }
  });
}

let prom=returnpromise(6);// assign promise to variable prom
console.log(prom) // returns Promise { 'resolved' }

// to get the data use it many times

prom.then(a=>console.log(a));

3
user1415066 On

You can wrap it in a function like this:

const getPromise = () => new Promise((resolve,reject) => {
    console.log('Promise executed')
    resolve()
})

Now you can call it multiple times:

getPromise().then(() => { // do something })
-1
Community On

Without input arguments in the Promise():

function Promise() {
  console.log('promise executed');
}

const aPromise = new Promise();

With input arguments in Promise(arguments)

function Promise(a) {
  console.log(a);
}

const aPromise = new Promise("promise executed");

Note: In Javascript is not used the operator "=>", the operator "=>" is used in C/C++, see more information here:

https://www.w3schools.com/jsref/jsref_operators.asp