Ideally, you should be listening for some event rather than polling, but on the understanding that this is a temporary workaround ...
new Promise()
runs its constructor synchronously and it would appear that controller.storage.users.get()
also runs its callback synchronously. The possibility of "Maximum call stack size exceeded" can be avoided by forcing the recursive getUser()
call to be made asynchronously and the simplest way to do that is to chain new Promise().then(/* recurse from here */)
.
function getUser(userId) {
return new Promise((resolve, reject) => {
controller.storage.users.get(userId, function(err, user) {
if (err) reject(err);
if (!user) reject(new Error('no user for id: ' + useId)); // this branch needs to be catered for
resolve(user); // make `user` available to the .then() below
});
}).then(function(user) {
return (user.orderData && user.orderData.pendingItem) || getUser(userId); // compact and safe
});
}
That should do the job but without the "Maximum call stack size" safeguard, stands a good chance of frying a processor or two for no good reason.
As suggested in the comments above, you can and probably should add some delay into the recursion :
function delay(t) {
return new Promise(function(resolve) {
setTimeout(resolve, t);
});
}
function getUser(userId) {
return new Promise((resolve, reject) => {
controller.storage.users.get(userId, function(err, user) {
if (err) reject(err);
if (!user) reject(new Error('no user for id: ' + useId)); // this branch needs to be catered for
resolve(user); // make `user` available to the .then() below
});
}).then(function(user) {
return (user.orderData && user.orderData.pendingItem) || delay(200).then(function() { // adjust the delay to maximum acceptable value
return getUser(userId);
});
});
}