Promise使用过程中常见错误及避坑指南 您所在的位置:网站首页 promise的过去式 Promise使用过程中常见错误及避坑指南

Promise使用过程中常见错误及避坑指南

2024-04-17 08:06| 来源: 网络整理| 查看: 265

JS 写的任何东西都会被执行并且会起作用,所以当我们追求高质量代码时,它应该是快速且无错误的。在使用 Promises时,我们可能很容易地犯一些错误,比如忘记输入代码的某些部分或使用不正确的东西。下面列出了开发过程中常见的 Promise 问题。

1、嵌套Promise

检查下面的代码

loadSomething().then(something => { loadAnotherThing().then(another => { doSomething(something, another) }).catch(e => console.error(e)) }).catch(e => console.error(e))

Promises 一个重要的作用就是为了修复“回调地狱”,上面的例子是用“回调地狱”风格编写的。要正确地重写代码,我们需要理解为什么原始代码是这样写的。在上述情况下,是需要在两个 Promise 的结果可用后做一些事情,因此进行了嵌套。可以使用Promise.all() 重写它:

Promise.all([loadSomething(), loadAnotherThing()]) .then(([something, another]) => { doSomething(something, another) }) .catch(e => console.error(e))

检查错误处理。当正确使用 Promises 时,只需要一个catch() 。

Promise 链还为我们提供了一个finally() 处理程序。它总是被执行,它有利于清理和一些总是被执行的最终任务,无论 Promise 被解决还是被拒绝。如下:

Promise.all([loadSomething(), loadAnotherThing()]) .then(([something, another]) => { doSomething(something, another) }) .catch(e => console.error(e)) .finally(() => console.log('Promise executed')) 2、断裂的Promise链

Promise 使用方便的主要原因之一是“promise-chaining”(链式结构),一种将 Promise 的结果传递到链中并在链的末端调用catch以在一个地方捕获错误的能力。让我们看看下面的例子:

function anAsyncCall() { const promise = doSomethingAsync() promise.then(() => { somethingElse() }) return promise }

上面代码的问题是执行somethingElse() 方法时,若该段内发生的错误将会丢失。那是因为我们没有从somethingElse() 方法中返回 Promise。默认情况下,.then() 总是返回一个 Promise,因此,在我们的例子中,返回的 Promise 将不会被使用,并且.then() 返回一个新的 Promise。我们丢失了方法somethingElse() 的执行结果。我们可以将其重写为

function anAsyncCall() { return doSomethingAsync() .then(somethingElse) .catch(e => console.error(e)) } 3、在 Promise 链中混合使用同步和异步代码

这是 Promises 最常见的错误之一。人们倾向于对所有事物使用 Promises 然后将它们



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有