javascript – 回复承诺?

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

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

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

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

解决方法:

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

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

.then(finalResult => {
  console.log(`Got the final result: ${finalResult}`);
})

所以你不能把另一个链接起来.然后再把它链接起来.

编辑
正如评论中所提到的那样.然后实际上总会返回另一个承诺.
但是有一个问题,如果你的解析回调不会返回任何内容(未定义),那么这个promise的调用者将被定义为未定义的参数.
所以基本上没有收获只是链“空”然后.

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

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

至于这句话:

arrow functions return implicitly when {} are left out

Arrow functions可以通过两种方式返回:

隐:

const func = () => 'hi there' // implicitly returns a string

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

const func = () => {'hi there'} // nothing is returned

明确:

当我们使用返回关键字时:

 const func = () => { return 'hi there'; } // explicitly returns a string

陷阱:
有时你想要返回一个对象,所以人们常常会犯一个错误:

const func = () => {a:1} // nothing is returned, just a meaningless label a

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

const func = () => ({ a:1 }) // implicitly returns an object

相关文章

最后的控制台返回空数组.控制台在ids.map函数完成之前运行va...
我正在尝试将rxJava与我已经知道的内容联系起来,特别是来自J...
config.jsconstconfig={base_url_api:"https://douban....
我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不...
config.jsconstconfig={base_url_api:"https://douban....
这是我的代码main.cpp:#include<string>#include<...