【问题标题】:Avoid callback hell and organising Node.js code避免回调地狱和组织 Node.js 代码
【发布时间】:2019-03-16 12:51:54
【问题描述】:

我正在尝试组织我的代码并想为每个 .then() 创建单独的函数,有些我无法做到,并且我的代码中断

请帮助我如何使事情正常进行

module.exports = function () {
   return new Promise((resolve, reject) => {
   try {
     const settings = blob();

    var {
    someObject
     } = JSON.parse(requestBody);
  var var1,var2,var3

  let somePromises = [];

  someObject.forEach((p) => {
    p.somepro = 'anything';
  });

  Promise.all(somePromises)
    .then((res) => {
      //replace cart item info
      res.forEach((r) => {
        someObject.forEach((so) => {
              so.info = ''
          });
        });
      });
    return require('/file1')(); // api call 1
    })
    .then((res) => {
      var2 = resp.something // local variable create above var2
      return require('/file2')(); // api call 2
    })
     .then((res) => {
      var3 = resp.something // local variable create above var3
      return require('/file2')(); // api call 3
    })
    .then((r) => {
      // some other maniuplation
    })
    .then(() => {
      // some calulation based on above responses and local variable 
      // assigned
      resolve({
        someObject,
        var1,
        var2
      });
    });
} catch (e) {
  reject(e);
}
 });
};

我试图让代码组织起来,并为每个承诺创建单独的函数,但没有弄明白如何以有组织和最佳实践的方式创建这个流程

【问题讨论】:

  • 你可以使用awaitasync
  • 你能分享一下与我的代码流相关的例子吗
  • 将此标记为转移到codereview.stackexchange.com
  • 你使用的是哪个版本的nodejs?您可以查看 async / await 并尝试使用承诺 /catch 来避免回调地狱。 Here 带有示例的文档链接。我还发现这个 tutorial 在 medium 上很有帮助!
  • @TomM OP 写道 “我无法做到的一些事情,以及我的代码中断。请帮助我如何使事情正常运行”... 代码审查不是寻求帮助以修复代码。

标签: javascript jquery node.js node-modules node-webkit


【解决方案1】:

首先不要resolve对象,这不是那么安全,因为then属性被Promise使用,如果它是一个函数。

console.loging ... 时,像这样返回的对象会显示详细信息(带有变量名)...

但是让我们假设,在您的承诺解决您的对象之前,某些方法会在您的对象中添加/替换then,然后您将对这些承诺进行一些调试。

阅读更多thenable objects here

我正在尝试组织我的代码并希望为每个 .then() 创建单独的函数

我创建了一个自定义方法,它按顺序为每个.then 传递 Promise.all 值。

您的要求是为每个.then 创建单独的函数。 只需复制粘贴 useIfFor 方法并根据需要重命名/更改它。

PS:您的代码中的一些块仍然存在...它们是无害的。

console.clear();
let module = {};
module.exports = () => {

  return new Promise((resolve, reject) => {

    const settings = {}; //blob();

    var {
      someObject
    } = JSON.parse(typeof requestBody !== 'undefined' ? requestBody : '[]');

    let somePromises = [
      Promise.resolve('some text'),
      Promise.resolve(100),
      Promise.resolve(10000),
    ];

    // var var1, var2, var3

    let stackVariables = [];

    // It passes the first value from Promise.all to the first 'then'
    // the 2nd value to the 2nd `then`
    // the 3rd value to the 3rd `then`
    // ...
    // the N-th value to the N-th `then`

    const useIfFor = (someStringOrNumber) => {

      return (res) => {

        // We'll use the first value of `res` and pass the rest of the values to the next `then`
        let [promiseValue, ...restOfTheValues] = res;


        // START HERE - To add your logic - `promiseValue` is your old 'res'
        console.log('Current `then` value:', promiseValue, '| Label:', someStringOrNumber);

        if (someStringOrNumber === 'my-first-then') {

          promiseValue = 'THIS VALUE IS MODIFIED';
          stackVariables.push(promiseValue); // first value from Promise.all

        } else if (someStringOrNumber === 'my-second-then') {

          stackVariables.push(promiseValue); // second value from Promise.all

        } else if (someStringOrNumber === 'my-third-then') {

          stackVariables.push(promiseValue); // third value from Promise.all

        } else {

          //  You can end it with resolve anywhere
          //resolve(stackVariables);

        }
        // END HERE


        if (typeof promiseValue === 'undefined') {

          // You reached the end, no more values.

          resolve(stackVariables);

        }

        // Passing the remaining values to the next `then`
        return restOfTheValues;

      }

    }

    Promise.all(somePromises)
      .then(useIfFor('my-first-then'))
      .then(useIfFor('my-second-then'))
      .then(useIfFor('my-third-then'))
      .then(useIfFor('done')) // <- here is the resolve because there isn't the 4th promise, therefore, no values
      .catch((err) => {
        reject(err);
      })

  });

};


(module.exports)()
.then(res => {

  console.log('res', res);

}).catch(console.error);

【讨论】:

    猜你喜欢
    • 2017-05-08
    • 2023-03-22
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    相关资源
    最近更新 更多