Create an AngularJS promise with no return value

I use $q to wrap the promise associated with the previous callback. However, the existing callback does not have a return value. It performs the function of success without parameters.

 angular.module('MyModule').service('MyService', function() { function initialize() { var deferred = $q.defer(); LegacyFactory.initialize( // 'void' Success Callback function () { deferred.resolve (/* WHAT DO I PUT HERE? */); }, // Error Callback function (errorCode) { deferred.reject(errorCode); }); return deferred.promise; } }); 

I cannot find the void resolve version in AngularJS docs. I can return a dummy value, but then clients can access this dummy value, which can cause confusion.

How to create an AngularJS clause without return value?

NOTE. The AngularJS question promising to return an empty object is completely different. This question returns a value in the resolve function.

+6
source share
1 answer

JavaScript does not have a void data type. Instead, JavaScript uses the primitive type undefined , which is used to represent a variable that is not assigned a value.

A method or statement that has no return value will return undefined . A function that does not use the return will return undefined . An argument that is not passed to the function will be undefined .

Hope you start to see consistent behavior here undefined .

 function foo(x) { console.log(x); } foo(); // will print undefined function zoom() {} console.log(zoom()); // will print undefined 

Therefore, when you use deferred.resolve() , you pass undefined as the value for the data argument.

To more accurately answer your question.

"How to create an AngularJS clause without return value?"

To write JavaScript code that gives the intention not to return a value for a promise. You have to write this.

 deferred.resolve(undefined); 

This makes it clear that there is no data.

Later in your callback you do not need to specify a data argument, but if you want, you can.

  foo().then(function(data){ if(typeof data === 'undefined') { // there is no data } else { // there is data }); 

if you always do not expect any data, then just do it.

 foo().then(function(){ // handle success }); 
+10
source

Source: https://habr.com/ru/post/975912/


All Articles