回头承诺了吗?

Dar*_*721 3 javascript promise

我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不明白它意味着什么的部分.

代码非常简单,但我不明白谨慎.回报承诺意味着什么?隐含地返回是什么意思?如果它是一个愚蠢的问题,请指向一些资源,我会将其标记为已关闭.

doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => {
console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);
Run Code Online (Sandbox Code Playgroud)

重要提示:始终返回promises,否则回调将不会链接,并且不会捕获错误(当省略{}时,箭头函数会隐式返回).

Sag*_*b.g 5

返回承诺通常意味着可以链接另一个.then.

在这里你没有返回任何东西:

.then(finalResult => {
  console.log(`Got the final result: ${finalResult}`);
})
Run Code Online (Sandbox Code Playgroud)

所以你不能.then在它之后链接另一个.

编辑
如评论中所述,.then实际上总是返回另一个承诺.
但是有一个问题,如果你的resolve回调不会返回任何东西(undefined)那么这个promise的调用者将undefined作为参数得到.
所以基本上没有收获只是链"空" then.

以下是此类案例的一个小型运行示例:

const promise = new Promise((resolve, reject) => {
  resolve("#1");
});

promise
  .then((result) => result)
  .then((result) => `${result} #2`)
  .then((result) => console.log(result))
  .then((result) => `${result} #4`) // <-- result === undefined
  .then((result) => console.log(result))
  .then((result) => console.log(result))
  .then((result) => '#7')
  .then((result) => console.log(result));
Run Code Online (Sandbox Code Playgroud)


至于这句话:

当省略{}时,箭头函数会隐式返回

箭头函数可以通过两种方式返回:

隐:

const func = () => 'hi there' // implicitly returns a string
Run Code Online (Sandbox Code Playgroud)

但是当有一个函数的主体时,{}没有返回任何内容:

const func = () => {'hi there'} // nothing is returned
Run Code Online (Sandbox Code Playgroud)

明确地:

当我们使用return关键词时:

 const func = () => { return 'hi there'; } // explicitly returns a string
Run Code Online (Sandbox Code Playgroud)

陷阱:
有时候你想要归还一个物体,所以人们常常会犯一个错误:

const func = () => {a:1} // nothing is returned, just a meaningless label a
Run Code Online (Sandbox Code Playgroud)

所以"修复"就是用一个表达式包装对象:

const func = () => ({ a:1 }) // implicitly returns an object
Run Code Online (Sandbox Code Playgroud)

  • 简洁明了.谢谢!! (2认同)