javascript - 有条件地调用一个 promise (或不调用),但将任一结果返回给另一个 promise

标签 javascript node.js asynchronous promise

尝试以不涉及嵌套 promise 的方式编写以下代码时遇到问题。

function trickyFunction(queryOptions, data) {
  return new Promise((resolve, reject) => {
    if (data) {
      resolve(data);
    } else {
      // ... a bunch of conditions to check and/or modify queryOptions. These checks and mods
      // are vital but only required if data is not passed in. ...
      if (anErrorHappensHere) {
        reject('Oh no, an error happened');
      }

      somePromise(queryOptions).then((result) => {
        resolve(result);
      });
    }
  }).then((result) => {
    criticalOperation1(result);
    // the code here is long and shouldn't be duplicated
  });
}

我真的不喜欢 somePromise 之后的 .then() 链,因为它在 new Promise 中,但我真的没有找到绕过它的方法。如果我从 promise 中取出条件,那么我将不得不复制 criticalOperation1 代码,这不是这里的一个选项。 else block 中的条件检查只有在未传入 data 时才会发生。在我的情况下不允许使用其他功能,也不允许使用 async/await就我而言。

有人有什么想法吗?我已经使用 Promises 一段时间了,但是这个让我很困惑。

最佳答案

在这种情况下,我会避免使用 new Promise 语法,而是尽早启动 promise 链

function trickyFunction(queryOptions, data) {
  return Promise.resolve()
    .then( () => {
      if (data) {
        return Promise.resolve(data);
      } else {
        // ... a bunch of conditions to check and/or modify queryOptions. These checks and mods
        // are vital but only required if data is not passed in. ...
        if (anErrorHappensHere) {
          // Could also just throw here
          return Promise.reject('Oh no, an error happened');
        }

        return somePromise(queryOptions);
      }
    })
   .then((result) => {
      criticalOperation1(result);
      // the code here is long and shouldn't be duplicated
    });
}

关于javascript - 有条件地调用一个 promise (或不调用),但将任一结果返回给另一个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54527749/

相关文章:

c# - 如何阻塞一个线程,直到另一个线程在 C# 中获得服务器响应

javascript - 如何在 R 中用传单制作的 map 上添加下载按钮?

javascript - 为网页的特定 block 导入 html 文件

javascript - 为什么这个错误没有出现在我的 Redux Action 的 Catch 中?

javascript - 在 Chrome 应用中使用 Fabric.js

javascript - ES6 类属性未定义

javascript - 如何像 Ember.js 那样抽象 ajax 请求的异步行为?

swift - 实现异步线程(使用 Swift 的 Xcode)

node.js - 在 NodeJs 中观察其他进程启动事件

node.js - nodejs stream.Readable.push() 返回值的语义是什么