避免回调地狱和组织Node.js代码

时间:2018-10-11 12:26:14

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

我正在尝试整理我的代码,并希望为每个.then()创建separte函数,这是我无法做到的,并且我的代码中断了

请帮助我如何使事情正常工作

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);
}
 });
};

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

1 个答案:

答案 0 :(得分:0)

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

这样返回的对象在console.log时显示详细的(带有变量名)

但是,假设在您的诺言解决您的对象之前,某些方法会使用一种方法在对象中添加/替换then,然后您将需要对这些诺言进行一些调试。

详细了解thenable objects here

  

我正在尝试整理我的代码,并希望为每个.then()创建separte函数

我创建了一个自定义方法,该方法为每个.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);