添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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 })
  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));

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

You should absolutley not overwrite the Promise-class with a function. Also => is used in javascript since ES5. – user1415066 Apr 30, 2019 at 12:10

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.