How does Promise run when .then method is not called?

巧了我就是萌 提交于 2021-02-18 20:51:10

问题


I create two promises, but I do not run the then method on those promises. Yet once the promise objects go out of scope, the promise code runs as if .then was called.

How is a Promise settled without a call to the .then method?

I am asking because I would like to load an array with Promise objects and then run the promises in sequence.

function promises_createThenRun() {
  const p1 = createPromise1();
  const p2 = createPromise2();

  console.log('before hello');
  alert('hello');
  console.log('after hello');
  // the two promises run at this point.  What makes them run?
}

function createPromise1() {
  let p1 = new Promise((resolve, reject) => {
    window.setTimeout(() => {
      console.log('timer 1');
      resolve();
    }, 2000);
  });
  return p1;
}

function createPromise2() {
  let p2 = new Promise((resolve, reject) => {
    window.setTimeout(() => {
      console.log('timer 2');
      resolve();
    }, 1000);
  });
  return p2;
}

回答1:


The code inside the Promise constructor runs when the promise is created and it runs synchronously which surprises some people. So even without then() everything still runs.

new Promise(resolve => console.log("running"))

Code in the callback for the setTimeout however, doesn't run until it's called, but it too will run even without the then()

new Promise(resolve => {
  console.log("promise created")
  setTimeout(() => console.log("this runs later"), 1000)
})



回答2:


When calling .then you just set up a "callback" which says what should happen after the promise is done. So the promise will be called, with or without declaring such callback.

Imagine the promise that calls a AJAX request. Calling .then and passing a function to it will make it run when the ajax call was finished (successfully or not as in timeout or other errors). But not calling .then will not stop the request to be run. You will simply not react to the results of the request.




回答3:


I thought, that "Promises won't run" if you don't call then/catch/finally on them, too. But if you consider, that these methods return new Promises, and according to your logic, you need to call then/catch/finally on these returned Promises in order to "run" them, you'll be stuck in an infinite loop)))



来源:https://stackoverflow.com/questions/51431235/how-does-promise-run-when-then-method-is-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!