不调用.then方法时,Promise如何运行? [英] How does Promise run when .then method is not called?

查看:25
本文介绍了不调用.then方法时,Promise如何运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个Promise,但是我没有在那些Promise上运行then方法.但是,一旦promise对象超出范围,promise代码就会像调用 .then 一样运行.

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.

如何在不调用 .then 方法的情况下解决 Promise ?

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

我之所以问是因为我想用 Promise 对象加载一个数组,然后依次运行promise.

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

推荐答案

Promise构造函数中的代码在创建promise时运行,并且同步运行,这使某些人感到惊讶.因此,即使没有 then(),所有内容仍然可以运行.

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"))

setTimeout 的回调中的

代码直到被调用后才运行,但是即使没有 then()

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

这篇关于不调用.then方法时,Promise如何运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆