Return resolved promise from rejected callback - promise

I'm not sure if I'm understanding a certain aspect of promises correctly and I couldn't find what I was looking for after a brief google/SO search.
Can a resolved promise returned to a rejected callback ever fire a resolved method later in the chain? Using jQuery deferreds (and it's deprecated pipe method) as an example:
x = $.Deferred();
x
.then(null,function() {
return $.Deferred().resolve();
})
.then(function() {
console.log('resolved');
},function() {
console.log('rejected');
});
The above code, logs rejected, I would've expected it to log resolved because the Deferred in the first error callback returns a resolved promise.
On the contrary, the same code using jQuery's deprecated pipe method logs, as I would've expected resolved.
x = $.Deferred();
x
.pipe(null,function() {
return $.Deferred().resolve();
})
.pipe(function() {
console.log('resolved');
},function() {
console.log('rejected');
});
Am I thinking about something wrong by trying to resolve a promise inside a rejected callback?

For anybody who has run into this same thought process, the following page helped me out: https://gist.github.com/domenic/3889970
Specifically:
...you can feed the return value of one function straight into another,
and keep doing this indefinitely. More importantly, if at any point
that process fails, one function in the composition chain can throw an
exception, which then bypasses all further compositional layers until
it comes into the hands of someone who can handle it with a catch.
It seems jQuery's pipe method was a violation of the Promise's specification.

Related

How to load JSON or see load-errors? [duplicate]

I am trying to load a GeoJSON file and to draw some graphics using it as a basis with D3 v5.
The problem is that the browser is skipping over everything included inside the d3.json() call. I tried inserting breakpoints to test but the browser skips over them and I cannot figure out why.
Code snippet below.
d3.json("/trip_animate/tripData.geojson", function(data) {
console.log("It just works"); // This never logs to console.
//...all the rest
}
The code continues on from the initial console.log(), but I omitted all of it since I suspect the issue is with the d3.json call itself.
The signature of d3.json has changed from D3 v4 to v5. It has been moved from the now deprecated module d3-request to the new d3-fetch module. As of v5 D3 uses the Fetch API in favor of the older XMLHttpRequest and has in turn adopted the use of Promises to handle those asynchronous requests.
The second argument to d3.json() no longer is the callback handling the request but an optional RequestInit object. d3.json() will now return a Promise you can handle in its .then() method.
Your code thus becomes:
d3.json("/trip_animate/tripData.geojson")
.then(function(data){
// Code from your callback goes here...
});
Error handling of the call has also changed with the introduction of the Fetch API. Versions prior to v5 used the first parameter of the callback passed to d3.json() to handle errors:
d3.json(url, function(error, data) {
if (error) throw error;
// Normal handling beyond this point.
});
Since D3 v5 the promise returned by d3.json() will be rejected if an error is encountered. Hence, vanilla JS methods of handling those rejections can be applied:
Pass a rejection handler as the second argument to .then(onFulfilled, onRejected).
Use .catch(onRejected) to add a rejection handler to the promise.
Applying the second solution your code thus becomes
d3.json("/trip_animate/tripData.geojson")
.then(function(data) {
// Code from your callback goes here...
})
.catch(function(error) {
// Do some error handling.
});
Since none of the answers helped, I had to find the solution on my own that works. I am using v4 and have to stick with it. The problem was (in my case) that d3.json worked the first time, but did not work the second or third time (with a HTML dropdown).
The idea is to use the initial function, and then simply to use a second function with
let data = await d3.json("URL");
instead of
d3.json("URL", function(data) {
Therefore, the general pattern becomes:
async function drawWordcloudGraph() {
let data = await d3.json("URL");
...
}
function initialFunction() {
d3.json("URL", function (data) {
...
});
}
initialFunction();
I have tried several approaches, and only this worked. Not sure if it can be simplified, please test on your own.

Bluebird promise was created but not returned warning [duplicate]

I was writing code that does something that looks like:
function getStuffDone(param) { | function getStuffDone(param) {
var d = Q.defer(); /* or $q.defer */ | return new Promise(function(resolve, reject) {
// or = new $.Deferred() etc. | // using a promise constructor
myPromiseFn(param+1) | myPromiseFn(param+1)
.then(function(val) { /* or .done */ | .then(function(val) {
d.resolve(val); | resolve(val);
}).catch(function(err) { /* .fail */ | }).catch(function(err) {
d.reject(err); | reject(err);
}); | });
return d.promise; /* or promise() */ | });
} | }
Someone told me this is called the "deferred antipattern" or the "Promise constructor antipattern" respectively, what's bad about this code and why is this called an antipattern?
The deferred antipattern (now explicit-construction anti-pattern) coined by Esailija is a common anti-pattern people who are new to promises make, I've made it myself when I first used promises. The problem with the above code is that is fails to utilize the fact that promises chain.
Promises can chain with .then and you can return promises directly. Your code in getStuffDone can be rewritten as:
function getStuffDone(param){
return myPromiseFn(param+1); // much nicer, right?
}
Promises are all about making asynchronous code more readable and behave like synchronous code without hiding that fact. Promises represent an abstraction over a value of one time operation, they abstract the notion of a statement or expression in a programming language.
You should only use deferred objects when you are converting an API to promises and can't do it automatically, or when you're writing aggregation functions that are easier expressed this way.
Quoting Esailija:
This is the most common anti-pattern. It is easy to fall into this when you don't really understand promises and think of them as glorified event emitters or callback utility. Let's recap: promises are about making asynchronous code retain most of the lost properties of synchronous code such as flat indentation and one exception channel.
What's wrong with it?
But the pattern works!
Lucky you. Unfortunately, it probably doesn't, as you likely forgot some edge case. In more than half of the occurrences I've seen, the author has forgotten to take care of the error handler:
return new Promise(function(resolve) {
getOtherPromise().then(function(result) {
resolve(result.property.example);
});
})
If the other promise is rejected, this will happen unnoticed instead of being propagated to the new promise (where it would get handled) - and the new promise stays forever pending, which can induce leaks.
The same thing happens in the case that your callback code causes an error - e.g. when result doesn't have a property and an exception is thrown. That would go unhandled and leave the new promise unresolved.
In contrast, using .then() does automatically take care of both these scenarios, and rejects the new promise when an error happens:
return getOtherPromise().then(function(result) {
return result.property.example;
})
The deferred antipattern is not only cumbersome, but also error-prone. Using .then() for chaining is much safer.
But I've handled everything!
Really? Good. However, this will be pretty detailed and copious, especially if you use a promise library that supports other features like cancellation or message passing. Or maybe it will in the future, or you want to swap your library against a better one? You won't want to rewrite your code for that.
The libraries' methods (then) do not only natively support all the features, they also might have certain optimisations in place. Using them will likely make your code faster, or at least allow to be optimised by future revisions of the library.
How do I avoid it?
So whenever you find yourself manually creating a Promise or Deferred and already existing promises are involved, check the library API first. The Deferred antipattern is often applied by people who see promises [only] as an observer pattern - but promises are more than callbacks: they are supposed to be composable. Every decent library has lots of easy-to-use functions for the composition of promises in every thinkable manner, taking care of all the low-level stuff you don't want to deal with.
If you have found a need to compose some promises in a new way that is not supported by an existing helper function, writing your own function with unavoidable Deferreds should be your last option. Consider switching to a more featureful library, and/or file a bug against your current library. Its maintainer should be able to derive the composition from existing functions, implement a new helper function for you and/or help to identify the edge cases that need to be handled.
Now 7 years later there is a simpler answer to this question:
How do I avoid the explicit constructor antipattern?
Use async functions, then await every Promise!
Instead of manually constructing nested Promise chains such as this one:
function promised() {
return new Promise(function(resolve) {
getOtherPromise().then(function(result) {
getAnotherPromise(result).then(function(result2) {
resolve(result2);
});
});
});
}
just turn your function async and use the await keyword to stop execution of the function until the Promise resolves:
async function promised() {
const result = await getOtherPromise();
const result2 = await getAnotherPromise(result);
return result2;
}
This has various benefits:
Calling the async function always returns a Promise, which resolves with the returned value and rejects if an error get's thrown inside the async function
If an awaited Promise rejects, the error get's thrown inside the async function, so you can just try { ... } catch(error) { ... } it like the synchronous errors.
You can await inside loops and if branches, making most of the Promise chain logic trivial
Although async functions behave mostly like chains of Promises, they are way easier to read (and easier to reason about)
How can I await a callback?
If the callback only calls back once, and the API you are calling does not provide a Promise already (most of them do!) this is the only reason to use a Promise constructor:
// Create a wrapper around the "old" function taking a callback, passing the 'resolve' function as callback
const delay = time => new Promise((resolve, reject) =>
setTimeout(resolve, time)
);
await delay(1000);
If await stops execution, does calling an async function return the result directly?
No. If you call an async function, a Promise gets always returned. You can then await that Promise too inside an async function. You cannot wait for the result inside of a synchronous function (you would have to call .then and attach a callback).
Conceptually, synchronous functions always run to completion in one job, while async functions run synchronously till they reach an await, then they continue in another job.

d3.json doesn't call callback function [duplicate]

I am trying to load a GeoJSON file and to draw some graphics using it as a basis with D3 v5.
The problem is that the browser is skipping over everything included inside the d3.json() call. I tried inserting breakpoints to test but the browser skips over them and I cannot figure out why.
Code snippet below.
d3.json("/trip_animate/tripData.geojson", function(data) {
console.log("It just works"); // This never logs to console.
//...all the rest
}
The code continues on from the initial console.log(), but I omitted all of it since I suspect the issue is with the d3.json call itself.
The signature of d3.json has changed from D3 v4 to v5. It has been moved from the now deprecated module d3-request to the new d3-fetch module. As of v5 D3 uses the Fetch API in favor of the older XMLHttpRequest and has in turn adopted the use of Promises to handle those asynchronous requests.
The second argument to d3.json() no longer is the callback handling the request but an optional RequestInit object. d3.json() will now return a Promise you can handle in its .then() method.
Your code thus becomes:
d3.json("/trip_animate/tripData.geojson")
.then(function(data){
// Code from your callback goes here...
});
Error handling of the call has also changed with the introduction of the Fetch API. Versions prior to v5 used the first parameter of the callback passed to d3.json() to handle errors:
d3.json(url, function(error, data) {
if (error) throw error;
// Normal handling beyond this point.
});
Since D3 v5 the promise returned by d3.json() will be rejected if an error is encountered. Hence, vanilla JS methods of handling those rejections can be applied:
Pass a rejection handler as the second argument to .then(onFulfilled, onRejected).
Use .catch(onRejected) to add a rejection handler to the promise.
Applying the second solution your code thus becomes
d3.json("/trip_animate/tripData.geojson")
.then(function(data) {
// Code from your callback goes here...
})
.catch(function(error) {
// Do some error handling.
});
Since none of the answers helped, I had to find the solution on my own that works. I am using v4 and have to stick with it. The problem was (in my case) that d3.json worked the first time, but did not work the second or third time (with a HTML dropdown).
The idea is to use the initial function, and then simply to use a second function with
let data = await d3.json("URL");
instead of
d3.json("URL", function(data) {
Therefore, the general pattern becomes:
async function drawWordcloudGraph() {
let data = await d3.json("URL");
...
}
function initialFunction() {
d3.json("URL", function (data) {
...
});
}
initialFunction();
I have tried several approaches, and only this worked. Not sure if it can be simplified, please test on your own.

In Jasmine derivative promises gets resolved incorrectly

Gist:
I spy on get method of my rest service:
spyOn(restService, 'get').and.callFake(function () {
return deferred.promise;
});
The method I am trying to test is myService.getFormData() that returns a chained promise:
function getFormData() {
var getPromise = this.restService.get(endPoint, params, true);
var processedDataPromise = then(successHandle, failHandler);
return processedDataPromise;
}
Back to Jasmine spec, I invoke getFormData function and make assertions:
var processedDataPromise = myService.getFormData();
processedDataPromise.then(function(data) {
expect(data).not.toBeNull();
});
deferred.resolve(testFormData);
$rootScope.$digest();
The Problem:
The above derivative promise (processedDataPromise) does indeed get resolved. However the 'data' passed to it is undefined. Is it anything to do with $digest cycles not doing its job in Jasmine?
Why does Jasmine not pass any data to the above derived promise.?
Further Note: The processedDataPromise is a completely new promise than the get returned promise.
It is a promise for processedData which as we can see is returned by successHandle (Definition not shown) once its parent getPromise gets resolved.
In UI everything works like a Charm.
Sorry for posting the question. The derivative promise indeed got the resolved data I was referring to. The problem was that I was incorrectly accessing the JSON data inside of successHandle.
As a result the 'successHandle' returned null and the the processedDataPromise got back undefined response.
Stupid mistake, very hard to find, but the best part is the learning and understanding of JS Promises.

Behavior on AngularJS deferred object

I was writing a function that will be executed asynchronously. Suddenly a question popped up in my mind.
Let's say I have the following function for updating student records.
module.factory('StudentService', function($http, $q) {
var service = {};
service.updateStudent = function(studentData) {
var deferred = $q.defer();
$http.put('http://www.example.com/student/update', studentData, {
headers: { 'Content-Type': 'application/json' }
}).success(function(response) {
if (response.success) {
deferred.resolve(response.data);
} else {
// I am not resolving the deferred object here
}
}).error(function(response) {
// I am not rejecting the deferred object here
});
return deferred.promise;
};
return service;
});
I want to ask,
What will happen to the deferred object if it is not resolved or rejected?
If a deferred object is not resolved or rejected, will it result in error for chains like StudentService.updateStudent(data).then(...)?
Is there any practical usage of neither resolving nor rejecting a deferred object?
If deferred is not resolved or rejected, the respective handlers will never be called.
No error - just will not call successive handlers in the chain.
Too broad for SO
Off-topic:
You don't need to use $q.defer when you use functions that already return a promise (like $http) - this is called a deferred anti-pattern. Simply return the original promise (or the promise created with .then).
Is there any practical usage of neither resolving nor rejecting a deferred object?
Yes, ensuring that any callbacks of a chained .then() or .catch() are never called.
Thus, there are three possible outcomes :
promise becomes "resolved": promise chain follows the success path.
promise becomes "rejected": promise chain follows the fail path.
promise remains "pending": nothing downstream happens, but still could if (references to) the promise still exist and it becomes either resolved or rejected.
That said, it's bad practice to leave a promise hanging. You should endeavour always to resolve or reject.
Off topic but related ...
Like any js object, a promise will be garbage collected when there are no references to it. However, due to the nature of promises, it is often very difficult to delete all references - they are not always lexically represented (in the application code). For example, "hidden" reference(s) to promise(s) lurk in every promise chain even where no explicit assignment is made. Every promise, whether it is lexically represented or not, will occupy memory.
Back on topic ...
A promise that will never settle, should either :
not be created (not always possible)
be deleted (seldom simple)
Personally, I feel that a lot more work needs to be done in this area.

Resources