繁体   English   中英

JavaScript:Promise.all 返回未定义

[英]JavaScript: Promise.all returning undefined

我正在尝试创建一个用户帐户创建脚本,重点是唯一的用户名 - 池中的前缀和后缀、现有用户名列表和保留用户名列表。

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

到目前为止,这是我的代码 - 它在AWS Lambda 上,并通过API Gateway进行了测试,如果这意味着什么:

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

有什么我想念的吗?

你的问题的原因是这个。 您需要运行这些函数,然后返回最终会解决的承诺:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM