Asynchronously solution to check data from databas

2019-03-04 10:05发布

What I want to do is asynchronously check from database and get a result from it? In my application I am trying to implement Asynchronously to resolve this steps as

  1. Check mobile numbers from database as JsonArray kinds of loop clause
  2. Create JsonArray from Result
  3. Print created array

I learned just enough about Promises to write the following connection, but then unfortunately my solution could't be implemented Asynchronously and I get multi row as result on the console.

1) First step is to pass data as json array to check mobile numbers from the database

registeredUsers(data)
    .then(function (value) {
        console.log('Contents: ' + value);
    }).catch(function (v) {
    console.log("faile");
});

2) After that I have two function inside Promise

function registeredUsers(data) {
    return new Promise(function (resolve, reject) {
        var accountNumbers = [];
        for (var i = 0; i < data.length; i++) {
            var mobileNumber = data[i].mobileNumber.substr(1, data[i].mobileNumber.length);
            checkUserMobileNumberAsEwallet(mobileNumber).then(function (mobileNumber) {
                accountNumbers.push({ewalletNumber: mobileNumber});
            }).catch(function (v) {
                reject(false)
            });
        }
        console.log(accountNumbers);
        resolve(accountNumbers);
    });
}

function checkUserMobileNumberAsEwallet(mobileNumber) {
    return new Promise(function (resolve, reject) {
        var query = "SELECT id FROM userEwallets WHERE ewalletNumber LIKE '%" + mobileNumber + "'";
        connection.query(query, function (err, results) {
            if (err) return reject(false);

            if (results.length > 0)
                resolve(mobileNumber);
        });
    });
}

What is my code problem? Why I can't implementing this?

1条回答
爷、活的狠高调
2楼-- · 2019-03-04 11:03

You can substitute Promise.all(), Array.prototype.map() for for loop

function registeredUsers(data) {
    return Promise.all(data.map(function(curr, i) {
        var mobileNumber = curr.mobileNumber.substr(1, curr.mobileNumber.length);
        return checkUserMobileNumberAsEwallet(mobileNumber)
        .then(function (_mobileNumber) {
            return {ewalletNumber: _mobileNumber};
        });
    }))
    .then(function(accountNumbers) {
        console.log(accountNumbers);
        return accountNumbers
    })
    .catch(function(err) {
        console.log(err);
    })
}

see also How do I return the response from an asynchronous call?

查看更多
登录 后发表回答