【问题标题】:How to create a Promise with default catch and then handlers如何使用默认捕获和处理程序创建 Promise
【发布时间】:2016-11-06 17:47:36
【问题描述】:

我正在创建一个使用 koa 和 babel async/await 的 API

我的控制器函数中的每个 promise 都如下所示:

async function ... {
    await Promise ... 
       .then(data => response function)
       .catch(err => err function)
}

每个 promise 都有完全相同的响应和错误函数。

有没有办法让我用相同的 then/catch 自动让每个 promise 解析(就像 promise 的默认解析函数)。

那么我的代码将如下所示:

async function ... {
    await Promise ... 
}

promise 会自动解析/捕获。

【问题讨论】:

  • 如果你有异步/等待,你不使用try { return response(await promise) } catch (e) { err(e) }吗?
  • 我在很多情况下都使用它,但在这种情况下我不是。
  • 这看起来像是 Koa 对我的误解。相反,您倾向于在上游使用中间件功能来处理下游的成功和失败,所有这些都在一个地方。使用中间件来分解重复的逻辑并保持路由最小化,这就是它的用途。
  • 你能举个例子吗?

标签: node.js promise async-await ecmascript-6 koa


【解决方案1】:

使用组合:

class MyPromise {
    constructor(executor) {
       this.promise = new Promise(executor);
       this.promise = this.promise
                          .then(defaultOnFulfilled, defaultOnReject);
    }
    then(onFulfilled, onRejected) {
       return this.promise.then(onFulfilled, onRejected);
    }
    catch(onRejected) {
       return this.promise.catch(onRejected);
    }
}

这会让你做什么:

new MyPromise((resolve, reject) => {... }).then(() => {
   // default actions have already run here
});

【讨论】:

  • 听起来像const applyDefaults = promise => promise.then(defaultOnFulfilled, defaultOnReject); 更容易编写和使用......
  • @Bergi 对,但我从 OP 的问题中了解到,他们希望能够做到 new Promise(executor) 并将其应用于所有链。
  • 我猜function PromiseWithDefaults(executor) { return new Promise(executor).then(defaultOnFulfilled, defaultOnReject); } 仍然会这样做 - 无需“子类化”Promise
  • 有没有办法完全避免调用.then().catch()
  • @asuna 你实际上不必打电话给thencatch,你只需要在任何地方使用MyPromise 来支持Promise,事情将自动为oyu 处理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 2019-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多