javascript承诺中“then block”和“then handler”有什么区别?

时间:2018-04-13 09:02:02

标签: javascript promise ecma

在此link的javascript中的promises文档中。写道:

  

使用已解决的承诺,'then'块将立即触发,        但它的处理程序将异步触发

// using a resolved promise, the 'then' block will be triggered instantly, 
// but its handlers will be triggered asynchronously as demonstrated by the console.logs

var resolvedProm = Promise.resolve(33);

var thenProm = resolvedProm.then(function(value){
    console.log("this gets called after the end of the main stack. the value 
    received and returned is: " + value);
    return value;
});

// instantly logging the value of thenProm
console.log(thenProm);

// using setTimeout we can postpone the execution of a function to the moment 
// the stack is empty

setTimeout(function(){
   console.log(thenProm);
});

// logs, in order:
// Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
// "this gets called after the end of the main stack. the value received and returned is: 33"
// Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: 33}

我不太明白它会说块会被触发但处理程序被触发异步的部分。我的问题是:

  1. 那么块是什么?它的处理程序是什么?它们有何区别?

  2. 每个触发什么?

  3. 当异步触发发生时,它会在所有
  4. 之后解决

    谢谢。

2 个答案:

答案 0 :(得分:1)

这句话有点令人困惑,这是我试图解释我认为它意味着什么。如果我在某处弄错了,请毫不犹豫地向我扔石头:)

.then()方法返回一个promise。我认为the 'then' block will be triggered instantly意味着.then方法在事件循环的当前运行中运行并立即返回承诺。但是,传递给then方法的回调会异步执行,即在以下的事件循环中执行。

因此,在该示例中,第一个记录的行是

  

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

因为这个:

var thenProm = resolvedProm.then(function(value){
    console.log("this gets called after the end of the main stack. the value 
    received and returned is: " + value);
    return value; });
运行

并返回promise,但是尚未执行返回值的回调,因此值未定义。

事件循环运行完成后,下一个循环开始并执行回调。此回调将值分配给promise并记录此行:

  

“这会在主堆栈结束后调用。收到的值   并返回:33“

最后,使用新分配的值记录promise本身:

  

承诺{[[PromiseStatus]]:“已解决”,[[PromiseValue]]:33}

更直接地回答您的问题:

  1. Then是Promise上的一个方法,它接受一个回调函数并返回另一个promise。当原始承诺得到解决时,将触发该函数。
  2. 当原始承诺被解决或拒绝时,触发在'then'方法中传递的回调函数。没有什么“触发”.then()方法本身,它只是一种方法。
  3. 解决承诺是触发回调的原因。
  4. 正如@Bergi所说,混淆的一个重要原因可能是“阻塞”这个词,这可能仅仅意味着“.then方法调用中的代码块。”

答案 1 :(得分:0)

  1. 然后block是Promise对象的方法。它用于注册回调,如果Promise被完成或拒绝,将调用它。
  2. 首次触发创建Promise实例的时间。当Promise将被解决或拒绝时,将调用处理程序
相关问题