首页 > 解决方案 > 避免回调地狱和组织 Node.js 代码

问题描述

我正在尝试组织我的代码并想为每个 .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);
}
 });
};

我正在尝试使代码组织并为每个承诺创建单独的功能,但不会感到困惑和困惑我如何以有组织和最佳实践的方式创建此流程

标签: javascriptjquerynode.jsnode-modulesnode-webkit

解决方案


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

像这样返回的对象在console.loging ...

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

阅读更多thenable objects here

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

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

您的要求是为每个.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);


推荐阅读