Looping with Promises - javascript

I'm in a scenario where I have to get data from the server in parts in sequence, and I would like to do that with the help of Promises. This is what I've tried so far:
function getDataFromServer() {
return new Promise(function(resolve, reject) {
var result = [];
(function fetchData(nextPageToken) {
server.getData(nextPageToken).then(function(response) {
result.push(response.data);
if (response.nextPageToken) {
fetchData(response.nextPageToken);
} else {
resolve(result);
}
});
})(null);
});
}
getDataFromServer().then(function(result) {
console.log(result);
});
The first fetch is successful, but subsequent calls to server.getData() does not run. I presume that it has to do with that the first then() is not fulfilled. How should I mitigate this problem?

Nimrand answers your question (missing catch), but here is your code without the promise constructor antipattern:
function getDataFromServer() {
var result = [];
function fetchData(nextPageToken) {
return server.getData(nextPageToken).then(function(response) {
result.push(response.data);
if (response.nextPageToken) {
return fetchData(response.nextPageToken);
} else {
return result;
}
});
}
return fetchData(null);
}
getDataFromServer().then(function(result) {
console.log(result);
})
.catch(function(e) {
console.error(e);
});
As you can see, recursion works great with promises.
var console = { log: function(msg) { div.innerHTML += "<p>"+ msg +"</p>"; }};
var responses = [
{ data: 1001, nextPageToken: 1 },
{ data: 1002, nextPageToken: 2 },
{ data: 1003, nextPageToken: 3 },
{ data: 1004, nextPageToken: 4 },
{ data: 1005, nextPageToken: 0 },
];
var server = {
getData: function(token) {
return new Promise(function(resolve) { resolve(responses[token]); });
}
};
function getDataFromServer() {
var result = [];
function fetchData(nextPageToken) {
return server.getData(nextPageToken).then(function(response) {
result.push(response.data);
if (response.nextPageToken) {
return fetchData(response.nextPageToken);
} else {
return result;
}
});
}
return fetchData(0);
}
getDataFromServer().then(function(result) {
console.log(result);
})
.catch(function(e) { console.log(e); });
<div id="div"></div>

Because your then statement doesn't pass a function to handle error cases, requests to the server for data can fail silently, in which case the promise returned by getDataFromServer will never complete.
To fix this, pass a second function as an argument to then, as below:
function getDataFromServer() {
return new Promise(function(resolve, reject) {
var result = [];
(function fetchData(nextPageToken) {
server.getData(nextPageToken).then(function(response) {
result.push(response.data);
if (response.nextPageToken) {
fetchData(response.nextPageToken);
} else {
resolve(result);
}
}).catch(function(error) {
//Note: Calling console.log here just to make it easy to confirm this
//was the problem. You may wish to remove later.
console.log("Error occurred while retrieving data from server: " + error);
reject(error);
});
})(null);
});
}

Related

declaring a function to wait for a promise

I have the following function:
function JSON_to_buffer(json) {
let buff = Buffer.from(json);
if ( json.length < constants.min_draft_size_for_compression) {
return buff;
}
return zlib.deflate(buff, (err, buffer) => {
if (!err) {
return buffer;
} else {
return BPromise.reject(new VError({
name: 'BufferError',
}, err));
}
});
}
I want to be able to run this but have it wait if it goes to the unzip call. I'm currently calling this within a promise chain and it's going back to the chain without waiting for this and returns after the previous promise chain has completed.
You can put that logic into a Promise along with an async function
function JSON_to_buffer(json) {
return new Promise(function (resolve, reject) {
let buff = Buffer.from(json);
if (json.length < constants.min_draft_size_for_compression) {
return resolve(buff);
}
zlib.deflate(buff, (err, buffer) => {
if (!err) {
resolve(buffer);
} else {
reject(err);
/*return BPromise.reject(new VError({
name: 'BufferError',
}, ));*/
}
});
});
}
async function main() {
try {
let buffer = await JSON_to_buffer(myJSON);
} catch (e) {
console.log(e.message);
}
}

Promise in a function

I have been trying to add promise into a function, I have this error TypeError: sort_devices_name.then is not a function, function get_groups_devices is calling sort_devices_name and sort_devices_name is the function that i want to use as the promise.
});
// Find devices object id with relation of groups
get_groups_devices();
}
});
function sort_devices_name() {
return new Promise(
function (resolve, reject) {
var d_ids = data.map(function (d) {
return ObjectId(d.d_id);
});
devices_lookup.find({"_id": {$in: d_ids}}).sort({"device_name": 1}).toArray(function (err, d_data) {
if (err) {
return res.send(JSON.stringify(err));
}
else {
var modify_data = [];
d_data.forEach(function (val) {
data.forEach(function (val2) {
if (val2.d_id == val._id) {
modify_data.push({g_id: val2.g_id, d_id: val._id});
}
});
});
resolve(modify_data);
}
});
});
}
// Find devices object id with relation of groups (if any) from devices group relation table.
function get_groups_devices() {
devices_group.find({"g_id": {$in: groups_ids}}, {
"d_id": 1,
"g_id": 1,
"_id": 0
}).toArray(function (err, d_data) {
d_data = sort_devices_name(d_data);
sort_devices_name.then(function (d_data) {
console.log(d_data);
if (err) {
return res.send(JSON.stringify(err));
} else {
You need to call sort_devices_name, not just refer to it; add ():
sort_devices_name().then(function...
// --------------^^
The function doesn't have a then property, but the promise it returns does.

Need help in resolving nested promises, Promises are not getting resolved

I have a service designed which takes some parameter and then loops through input array, and find out which item is empty and then add those to and array and then after $q.all resolved it should give me the array of empty items.
input is array of items
function getElements(inputs) {
var elements= [],
promise, whenPromise,
promises = [],
mainPromise = $q.defer();
if (inputs.length === 0) {
mainPromise.resolve(elements);
return mainPromise.promise;
}
angular.forEach(inputs, function (input) {
promise = getPromises(input);
whenPromise = $q.resolve(promise).then(function (response) {
$timeout(function() {
if (response.isEmpty) {
**//perform action with the response.data;**
}
});
}, function () {
});
promises.push(whenPromise);
});
$q.all(promises).finally(function () {
mainPromise.resolve(outdatedEntities);
});
return mainPromise.promise;
}
function getPromises(input) {
var deferred = $q.defer();
someSerivce.getItemDetails(input.Id).then(function (value) {
if (value === null) {
$timeout(function () {
deferred.resolve({data: input, isEmpty: true});
});
} else {
//have item locally, but need to see if it's current
input.isEmpty().then(function (isEmpty) {
$timeout(function () {
deferred.resolve({data: input, isEmpty: isEmpty});
});
}, function (error) {
deferred.reject(error);
});
}
});
return deferred.promise;
}
Now, the problem is the $q.all is never resolved. Even though all the internal promises are getting resolved.
This should work:
function getElements(inputs) {
var elements = [],
promise, whenPromise,
promises = [],
mainPromise = $q.defer();
if (inputs.length === 0) {
mainPromise.resolve(elements);
return mainPromise.promise;
}
angular.forEach(inputs, function (input) {
promise = getPromises(input);
whenPromise = promise.then(function (response) {
if (response.isEmpty) {
* *//perform action with the response.data;**
}
}, function () {
});
promises.push(whenPromise);
});
return $q.all(promises).finally(function () {
return outdatedEntities;
});
}
function getPromises(input) {
return someSerivce.getItemDetails(input.Id).then(function (value) {
if (value === null) {
return {data: input, isEmpty: true};
} else {
//have item locally, but need to see if it's current
return input.isEmpty().then(function (isEmpty) {
return {data: input, isEmpty: isEmpty};
}, function (error) {
return error;
});
}
});
}

Promise inside promise

I am trying to write this code with Promise. but I don't know how to write promise inside Promise and loop.
I tried to think like this but insertBook function become asynchronously.
How can I get bookId synchronously?
update: function(items, quotationId) {
return new Promise(function(resolve, reject) {
knex.transaction(function (t) {
Promise.bind(result).then(function() {
return process1
}).then(function() {
return process2
}).then(function() {
var promises = items.map(function (item) {
var people = _.pick(item, 'familyName', 'firstNumber', 'tel');
if (item.type === 'book') {
var book = _.pick(item, 'name', 'bookNumber', 'author');
var bookId = insertBook(t, book);
var values = _.merge({}, people, {quotation: quotationId}, {book: bookId});
} else {
var values = _.merge({}, people, {quotation: quotationId});
}
return AModel.validateFor(values);
});
return Promise.all(promises);
}).then(function(items) {
var insertValues = items.map(function (item) {
return People.columnize(item);
});
return knex('people').transacting(t).insert(insertValues);
}).then(function() {
return process5
}).then(function() {
...........
}).then(function() {
t.commit(this);
}).catch(t.rollback);
}).then(function (res) {
resolve(res);
}).catch(function(err) {
reject(err);
});
});
}
function insertBook(t, book){
return Promise.bind(this).then(function () {
return Book.columnizeFor(book);
}).then(function (value) {
return knex('book').transacting(t).insert(value, "id");
});
}
You dont need to get bookid synchronously, you can handle it asynchronously correctly. Also, it is possible you want all book insertions happen sequentially, so I refactored the Promise.all part. (done that just to give you an idea. Promise.all should work fine if insertions in parallel are allowed). Furthermore, I think you shouldn't use Promise.bind. To be honest I dont even know what it does, one thing for sure: it doesn't work with standard promises. So here is an example how I think it should work:
update: function(items) {
return new Promise(function(resolve) {
knex.transaction(function (t) {
resolve(Promise.resolve().then(function() {
return process1;
}).then(function() {
return process2;
}).then(function() {
var q = Promise.resolve(), results = [];
items.forEach(function (item) {
q = q.then(function() {
var book = _.pick(item, 'name', 'bookNumber', 'author');
return insertBook(t, book);
}).then(function(bookId) {
var people = _.pick(item, 'familyName', 'firstNumber', 'tel');
var values = _.merge({}, people, {book: bookId});
return AModel.validateFor(values);
}).then(function(item) {
results.push(item);
});
});
return q.then(function() {
return results;
});
}).then(function(items) {
return process4
}).then(function() {
t.commit(result);
}).catch(function(e) {
t.rollback(e);
throw e;
}));
});
});
}
function insertBook(t, book){
return Promise.resolve().then(function () {
return Book.columnizeFor(book);
}).then(function (value) {
return knex('book').transacting(t).insert(value, "id");
});
}
Assuming that insertBook returns a promise you could do
var people = _.pick(item, 'familyName', 'firstNumber', 'tel');
if (item.type === 'book') {
var book = _.pick(item, 'name', 'bookNumber', 'author');
return insertBook(t, book)
.then(bookId => _.merge({}, people, {quotation: quotationId}, {book: bookId}))
.then(AModel.validateFor)
} else {
return Promise.resolve(_.merge({}, people, {quotation: quotationId}))
.then(AModel.validateFor)
}

Nested promise in a for loop not behaving as expected

I am having trouble extending a Promise inside a .then(). I am trying to perform DB updates in a for-loop and then close the database after all records are processed. However the application exits with process.exit() right away which means that process.exit() was executed even before all db updates were finished. I am pretty sure I am doing something wrong with the nested promise.
var myDB;
function doSomething() {
return MongoClient.connect(DB_CONNECTION).then(function(db) {
myDB = db;
var collection = db.collection(COLLETION_NAME);
for (var i = 0; i < 10; i++) {
promise.then(function{
collection.update({
symbol: items[i].symbol
}, {
$set: {
value: 123
}
}, {
upsert: true
});
});
}
})
}
var promise = doSomething();
promise.then(function(){
console.log("DONE");
myDB.close();
process.exit();
});
It looks like you are getting a promise back from the MongoClient.connect method so why not use that to chain together. I've put a quick sample together below based on your code:
function doSomething(db) {
return new Promise(function(resolve, reject){
var collection = db.collection(COLLETION_NAME);
for (var i = 0; i < 10; i++) {
collection.update({
symbol: items[i].symbol
}, {
$set: {
value: 123
}
}, {
upsert: true
});
}
resolve(db);
})
}
function connectToDB() {
return MongoClient.connect(DB_CONNECTION);
}
function closeDB(db) {
return new Promise(function(resolve, reject){
db.close();
resolve();
});
}
connectToDB().then(function(db){
return doSomething(db);
}).then(function(db){
return closeDB(db);
}).then(function(){
console.log("DONE");
process.exit();
}).catch(function(error){
console.log('Something went wrong: ' + error);
});
Updated code as per #RayonDabre 's suggestion
function doSomething() {
return MongoClient.connect(DB_CONNECTION).then(function(db) {
myDB = db;
var collection = db.collection(COLLECTION_NAME);
var promises = [];
for (var i = 0; i < 10; i++) {
var innerPromise = collection.update({
symbol: items[i].symbol
}, {
$set: {
value: 123
}
}, {
upsert: true
});
promises.push(innerPromise);
}
return Promise.all(promises);
});
}
var promise = doSomething();
promise.then(function(){
console.log("DONE");
myDB.close();
process.exit();
});

Categories

Resources