JavaScript:Promise.all返回未定义

时间:2018-08-31 09:19:17

标签: javascript promise

我正在尝试创建一个专注于唯一用户名的用户帐户创建脚本-池中的前缀和后缀,现有用户名列表以及保留用户名列表。

这只是开始(还没有保存!),已经需要三个连接,所以我只是决定看看我是否可以编写一个可以处理所有功能的函数。

到目前为止,这是我的代码-它位于 AWS Lambda 上,并通过 API网关进行了测试,如果有什么意思,

const dbConnMysql = require('./dbController');
var methods = {
    createUser: function() {
        let getPrefixSuffixList = new Promise((resolve, reject) => {
            let connection = dbConnMysql.createConnection();
            dbConnMysql.startConnection(connection)
            .then((fulfilled) => {
                let table = 'userNamePool';
                return dbConnMysql.selectFrom(connection, table, '*', null);
            })
            .then((fulfilled) => {
                console.log(fulfilled);
                return dbConnMysql.closeConnection(connection)
                .then((fulfilled) => {
                    resolve(fulfilled);
                });
            })
            .catch((error) => {
                console.log(error);
                reject(error);
            });
        });

        let getTempUserNameList = new Promise((resolve, reject) => {
            // Same as getPrefixSuffixList, different table
        });

        let getRealUserNameList = new Promise((resolve, reject) => {
            // Same as getPrefixSuffixList, different table
        });

        return new Promise((resolve, reject) => {
            Promise.all([getPrefixSuffixList, getTempUserNameList, getRealUserNameList])
            .then((fulfilled) => {
                console.log(fulfilled[0]);
                console.log(fulfilled[1]);
                console.log(fulfilled[2]);
                let response = {
                    "statusCode": 200,
                    "headers": {"my_header": "my_value"},
                    "body": {"Prefix Suffix":fulfilled[0], "Temp UserName List":fulfilled[1], "Real UserName List":fulfilled[2]},
                    "isBase64Encoded": false
                };
                resolve(response);
            })
            .catch((error) => {
                let response = {
                    "statusCode": 404,
                    "headers": {"my_header": "my_value"},
                    "body": JSON.stringify(error),
                    "isBase64Encoded": false
                };
                reject(response);
            })
        });
    }
};    
module.exports = methods;

此功能在index.js的其他地方调用:

app.get('/createUserName', function (req, res) {
    var prom = Register.createUser();
    prom.then((message) => {
        res.status(201).json(message);
    })
    .catch((message) => {
        res.status(400).json(message);
    });
})

现在我不能完全确定我对Promise.All所做的一切是否正确,但是据我所知,如果一个承诺失败,Promise.All也会失败。

但是,个人承诺确实可以很好地工作,并从数据库中注销相应的结果。但是在Promise.All内部,所有内容都只注销了undefined

有什么我想念的吗?

1 个答案:

答案 0 :(得分:2)

问题的原因是这样的。您需要运行函数,这些函数然后返回最终将解决的promise:

    Promise.all([getPrefixSuffixList(), getTempUserNameList(), getRealUserNameList()])

这里还有一些更简单的代码。通常,不需要new Promise()。此代码可能会解决其他问题。另外,undefined可以从代码的任何部分进行打印,请确保将其打印在您认为合适的位置。

// Dummy MySQL connector
const dbConnMysql = {
  createConnection: () => 'Connection',
  startConnection: conn => new Promise(resolve => setTimeout(resolve, 100)),
  selectFrom: (conn, t, q, n) =>
    new Promise(resolve =>
      setTimeout(() => {
        console.log(`${conn}: SELECT ${q} FROM ${t}`);
        resolve(`x ${t} RECORDS`);
      }, 100)
    ),
  closeConnection: conn => new Promise(resolve => setTimeout(resolve, 100)),
};

const methods = {
  createUser() {
    const getPrefixSuffixList = () => {
      const connection = dbConnMysql.createConnection();
      return dbConnMysql
        .startConnection(connection)
        .then(() => {
          const table = 'userNamePool';
          return dbConnMysql.selectFrom(connection, table, '*', null);
        })
        .then(fulfilled => {
          console.log(fulfilled);
          return dbConnMysql.closeConnection(connection).then(() => fulfilled);
        })
        .catch(error => {
          console.log(error);
          // Note: this catch will stop the error from propagating
          // higher, it could also be the cause of your problem.
          // It's okay to catch, but if you want the error to
          // propagate further throw a new error here. Like this:
          throw new Error(error);
        });
    };

    const getTempUserNameList = () => {
      // Same as getPrefixSuffixList, different table
    };

    const getRealUserNameList = () => {
      // Same as getPrefixSuffixList, different table
    };

    return Promise.all([getPrefixSuffixList(), getTempUserNameList(), getRealUserNameList()])
      .then(fulfilled => {
        console.log('fulfilled[0]: ', fulfilled[0]);
        console.log('fulfilled[1]: ', fulfilled[1]);
        console.log('fulfilled[2]: ', fulfilled[2]);
        return {
          statusCode: 200,
          headers: { my_header: 'my_value' },
          body: {
            'Prefix Suffix': fulfilled[0],
            'Temp UserName List': fulfilled[1],
            'Real UserName List': fulfilled[2],
          },
          isBase64Encoded: false,
        };
      })
      .catch(error => ({
        statusCode: 404,
        headers: { my_header: 'my_value' },
        body: JSON.stringify(error),
        isBase64Encoded: false,
      }));
  },
};

methods.createUser();