mahdi pishguy mahdi pishguy - 3 months ago 9
Javascript Question

Asynchronously solution to check data from database kinds of loop cluase

what i want to do Asynchronously check from database and get result of that? in my application i', trying to implementing

Asynchronously
to resolve this steps as


  1. check mobile numbers from database as
    JsonArray
    kinds of loop cluase

  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 implementing
Asynchronously
and i get multi row as result on console

1) Fisrt step to pass data as json array to check mobile numbers from database

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


2) after that i have two function which they are 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);
});
});
}


whats my code problem which i cant implementing that?

Answer

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?

Comments