理解 promise 然后处理程序的语法和语义

Understanding promise then handler syntax and semantics

我想创建一个启动进度条效果的函数,创建并执行“ajax”调用,从结果中提取 html 并停止进度条效果 - 然后 return进一步处理的承诺:

function myStart()
{
   ProgressBar_ON(); // initiates some effect on html that ajax call is on the way
   var promise = fetch(url, {headers:'Accept': 'text/html'});
   return promise
          .then(resp => resp.text())
          .then(resp => { ProgressBar_OFF(); return resp; });
}

我想这样称呼它:

myStart()
 .then( resp => $("#placeholder).html(resp) )
 .then( ... )

问题出在 myStart 函数内部。最后一个“then”我尝试用三种方式写:

// #1 one command only - BAD
.then( resp => ProgressBar_OFF() )
// #2 arrow expression - BAD
.then( resp => { ProgressBar_OFF(); return resp; } )
// #3 old way - but this one works well
.then( function(resp) { ProgressBar_OFF(); return resp; } )

谁能解释为什么#1 和#2 与#3 是错误的?或者至少可以建议我阅读有关该主题的一些内容?

据说 .then 必须 return 一个 promise(它本身是一个具有 2 种可能状态的对象),如果我在第一个中检查 resp (.then(resp => resp.text()) 我可以看到它是一个相当复杂的对象(由 fetch 本身创建)。要提取 resp.text() 我可以想象这是“return 值” this then, which is given to the very next one, so resp => $("#container").html(resp) 可以工作。那为什么 #2 不会?

我在一些示例中看到,以下内容在 then 中很常见 - 这(对我而言)意味着执行 console.log,然后执行 returns ???响应本身?如果那么为什么#1 不会工作?注意:ProgressBar_OFF() 函数不包含“return”,所以 returns ??作废?!

.then( resp => console.log( resp ) )

当我读到箭头表达式时:“resp => ProgressBar_OFF()”意味着它 return 由 ProgressBar_OFF 编辑的值 return () 本身。暗示return。我可以接受,在这种情况下它很糟糕,因为 OF​​F() 函数 return 什么都没有。 console.log 调用是如何工作的?在这种情况下 ".then( resp => $("#placeholder).html(resp) )" 也不会很好:(

我害怕陷入javascript某个地方:(有人可以伸出援手吗?

给定:

const returnValue = aPromise.then( callbackFunction );

aPromise 解析时 callbackFunction 将被调用,传递给它的第一个参数将是 aPromise 的解析值。

then() 的 return 值将分配给 returnValue。该值将是解析为 callbackFunction 的 return 值的承诺。


var promise = fetch(url, {headers:'Accept': 'text/html'});
return promise
      .then(resp => resp.text())
      .then(resp => { ProgressBar_OFF(); return resp; });

在这行代码中 promise 是一个解析为 Response 对象的承诺。

第 2 行将该 Response 分配给 resp,然后对其调用 text()。 return 的值是一个解析为响应主体内容的承诺。

在第 3 行中,文本内容被分配给 resp。然后你调用 ProgressBar_OFF()。然后你 return 文字。

所以第二个 then return 是一个解析为相同文本的承诺。然后通过 return 语句从 myStart 函数中 returned。


// #1 one command only - BAD
.then( resp => ProgressBar_OFF() )

此处箭头函数 return 是 ProgressBar_OFF() 的 return 值。值 resp 丢失,因为它没有 return 到链中的下一个 then

// #2 arrow expression - BAD
.then( resp => { ProgressBar_OFF(); return resp; } )
// #3 old way - but this one works well
.then( function(resp) { ProgressBar_OFF(); return resp; } )

这两个是等价的。他们都应该工作。两者都调用 ProgressBar_OFF 然后 return 传入的值。