using bluebird with undefined success callback function - javascript

I am using bluebird library over memcached.
memcached.set('foo', 'bar', 10, function (err) { /* stuff */ });
this function does not call success callback in second parameter so seems like .then(res) function does not getting called.
Promise.promisifyAll(memcached);
memcached.setAsync(hashedCacheKey, obj).then(function (res) {
resolve(res);
}).catch(function (err) {
reject(err, null);
});
is there any way for me to handle uncalled success event?

The primary issue here is that you're not providing a timeout argument to memcached.setAsync, but it's a mandatory argument for memcached.set. These two lines are equivalent:
memcached.set("foo", "bar", () => { /* this is never called */ });
memcached.setAsync("foo", "bar").then(() => { /* this is never called, either */ })
Add a timeout argument and your code should work as expected.

Related

Handle ajax errors and execute the promise chain

I'm trying to provide a fallback for the failed ajax requests.
I want a global solution so I won't have to change every call in the code.
I tried providing an error handler to ajaxSetup, but the problem is I couldn't execute the chained callbacks.
$.ajaxSetup({
error: function() {
console.error('Error occurred')
return $.getJSON('https://jsonplaceholder.typicode.com/todos/1')
}
})
$.getJSON('https://jsonplaceholder.typicode.com/todos/0') // Id doesn't exist
.then(todo => console.log(todo))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Expected output
Error occurred
{
"id": 1,
"title": "...",
...
}
From jQuery 3.0 the callback method accepted are: done, always, fail.
So, i would have called the callback fail and in the inner, i resend the ajax call wrapped into a properly function with dynamic id
const submit = (id) => {
const xhr = $.getJSON(`https://jsonplaceholder.typicode.com/todos/${id}`)
.done(todo => console.log(todo))
.fail(err => { console.error(err); submit(id++); });
};
submit(0);

Electron js win.webContents.print callback function doesn't work?

I am working on an application with Electron js and Vue js. I need to print the Synchronous request sent by Renderer with the print function. According to the result, I have to transmit the result to the renderer over the backend. Therefore, I use the callback function of the print function. But when I use this function, the print method does not work. I shared the codes below. Could there be an error?
ipcMain.on("set-print", function(event, arg) {
let options = {
silent: true,
deviceName: arg,
};
win.webContents.print(options, function(success) {
event.returnValue = success;
});
});
Try Promise function
win.webContents.print(options)
.then((success)=>{
console.log(success);
})
.catch((err)=>{
console.log(err)
});
https://www.electronjs.org/docs/api/webview-tag#webviewprintoptions

Javascript - What is happening to the callbacks in async parallel in this example?

I'm trying to teach myself javascript, and I am working my way through Mozilla's Express tutorial, and I came across this piece of code that is confusing me.
Each function in the object that is being passed as the first argument in async.parallel is being passed a callback argument. I'm learning about callbacks and how they work. Normally when I see a callback, it's invoked later on in the function that it's passed into something like callback(), or callback(null, result), but I don't see that here. Any idea why that's the case?
Just as a heads up, the count method (from the Mongoose api) accepts two arguments, the second one being a callback.
exports.index = function(req, res) {
async.parallel({
book_count: function(callback) {
Book.count(callback);
},
book_instance_count: function(callback) {
BookInstance.count(callback);
},
book_instance_available_count: function(callback) {
BookInstance.count({status:'Available'},callback);
},
author_count: function(callback) {
Author.count(callback);
},
genre_count: function(callback) {
Genre.count(callback);
},
}, function(err, results) {
res.render('index', { title: 'Local Library Home', error: err, data: results });
});
};
In the docs, you can read up on async.parallel.
The reason you don't see callback(null, result), is because the callback is being directly passed to mongoose. It is important to note, that it is mongoose that is invoking the callback function - not your code.
For example:
book_count: function(callback) {
Book.count(callback);
},
Is the same as writing
book_count: function(callback) {
Book.count(function(error, result) {
callback(error, result);
});
},
As you can see, the second example only adds a "wrapper"-function - which is not really needed. It is much more readable to just pass along the callback to mongoose (which has the same convention of accepting error as the first argument, and result as the second).

AngularJS : promises, can you pass a promise back after using .then()?

I'm still new to Angular and promises so I hope I have the correct idea here.
I currently have a data layer service which uses restangular to get some data, then returns a promise, like this...
dataStore.getUsers = function (params) {
return users.getList(params);
};
Then, my controller which has called this function receives a promise back, like this...
$dataStore.getUsers(params).then(function (response) {
$scope.users = response;
}, function(response) {
$log.error("Get users returned an error: ", response);
});
This is working well, but I'd like to use the promise inside of my datastore before passing it back. I'd like to use the .then() method to check if it failed and do some logging, then, from the sucess function and from the failure function I'd like to return the original promise back to my controller.
My controller would then be able to use the .then() method like it already is, in fact, I don't want my controller code to change at all, just my datastore code.
Here's some semi-pseudo code to show what I'd like my datastore function to do...
dataStore.getUsers = function (params) {
users.getList(params).then(function (response) {
$log("server responded")
return original promise;
}, function(response) {
$log.error("server did not respond");
return original promise;
});
};
You were actually not far off at all in your pseudo code. Promises chain:
dataStore.getUsers = function (params) {
return users.getList(params).then(function (response) {
$log("server responded")
return response;
}, function(failure) {
$log.error("server did not respond");
// change to throw if you want Angular lever logs
return $q.reject(failure);
});
};
The controller now gets resolved/rejected with the same value. The log requires tapping into the promise so you must add a .then handler to deal with it. Other promise libraries have convinicene methods for this but $q is minimalistic in this regard.
Alternatively, you can use nicer catch syntax, as well as propagate the errors to your logs:
dataStore.getUsers = function (params) {
return users.getList(params).then(function (response) {
$log("server responded")
return response;
}).catch(function(failure) {
$log.error("server did not respond");
throw failure;
});
};

How can I analyse my JS program to ensure a particular method is always called with 2 arguments?

We're using promises in an AngularJS project and want to ensure that the then method is always called with 2 arguments, the 2nd being an error handler, like so:
$http.get(url).then(function () {
console.log('hooray!');
}, function (error) {
console.log('boo! error');
});
We're using jshint on the project. Can that perform this analysis?
Some calls to then do not require an error handler, i.e. in a chain of handlers:
$http.get(url1).then(function () {
console.log('hooray!');
return $http.get(url2);
}).then(function () {
console.log('hooray again! all our data loaded');
}, function (error) {
console.log('boo! error in one of our 2 requests');
});
We could mark these up using jshint's /* jshint ignore:start */ comments or similar.

Categories