javascript - 兑现 promise ?

标签 javascript promise

我在 MDN 中阅读有关 javascript 的内容时遇到了谈论 promise 的部分,但不明白它的含义。

代码非常简单,但是我不明白警告这个词。兑现 promise 是什么意思?隐式返回是什么意思?如果这是一个愚蠢的问题,请指出一些资源,我会将其标记为已关闭。

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

重要提示:始终向上返回 promise ,否则回调不会链接,也不会捕获错误(箭头函数在 {} 被遗漏时隐式返回)。

最佳答案

返回一个 promise 通常意味着能够链接另一个.then

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

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

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

编辑
如评论中所述,.then 实际上总是返回另一个 promise。
但是有一个问题,如果你的 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));


至于这个声明:

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

明确地:

当我们使用return 关键字时:

 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

关于javascript - 兑现 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48290208/

相关文章:

javascript - 从街景中的像素获取航向和俯仰

javascript - D3.js 4 与 AngularJS 1.5(组件或指令?)

javascript - 如何将 $promise 返回的数据分配给全局变量

javascript - bluebird 是否具有用于在 promises 中包装函数的说服函数?

javascript - 在 Protractor 中使用带有 promise 的页面对象模式

javascript - 使用 Promise 和递归查找多个随机数据

javascript - 复选框状态不会改变 react

javascript - 接受通用参数并返回通用值的函数

javascript - 一旦所有延迟完成就调用一个方法?

javascript - 如何通过ajax发送文件)而不使用html表单?