Promise is not working properly saveService is called before promise resolved means all documents get uploaded, but when I log the data in the saveService it shows the uploaded docs unable to figure out the issue, please let me know where i am wrong
//file upload
$scope.fileObj = {};
$scope.documentUploaded = [];
var uploadFile = function (type) {
var file = $scope.fileObj[type];
//service to upload file
fileService.uploadDocument(file)
.success(function (data, status) {
console.log("uploaded successfully", data);
$scope.documentUploaded.push({
doc: {
fileName: data.name,
path: data.path
}
});
})
.error(function (data, status) {
});
}
$scope.save = function () { //on click of submit, save() is called
var defer = $q.defer();
var promises = [];
//looping to upload files
angular.forEach($scope.documentList, function (doc) {
if ($scope.fileObj[doc.type]) {
promises.push(uploadFile(doc.type));
}
});
//this will save data when promise will get complete
var saveData = function () {
var dataToSave = {
//other fields
documents: $scope.documentUploaded
};
saveService.saveApi(dataToSave)
.success(function () {
defer.resolve('data saved');
})
.error(function () {
defer.reject("something went wrong");
});
}
$q.all(promises).then(saveData);
return defer;
}
uploadFile() needs to return a promise (that is resolved when its work is done) for $q.all(promises) to work.
Right now it isn't returning anything so you're passing $q.all() an array of undefined values. Since there are no promises in that array, $q.all() executes the .then() handler immediately.
Here's a condensed version of the problem:
var promises = [];
...forEach(function() {
promises.push(uploadFile(doc.type));
});
$q.all(promises).then(saveData);
So, you're pushing into the promises array the return value from uploadFile(). But uploadFile() doesn't even return anything. So, you're pushing in undefined. Then, you pass an array of undefined values to $q.all when it's expecting an array of promises.
So, to make this logic work, you need uploadFile() to return a promise that gets resolved when that instance of uploadfile() is done with its async work.
If fileService.uploadDocument() already returns a promise, you can just return that promise. If not, then you can create one at the beginning of uploadFile() and return it at the end and then resolve or reject it in the .success() and .error() handlers.
If fileService.uploadDocument() can already make a promise, then the preferred solution would be to use that promise (I don't know that API so don't know how it works). If it can't make a promise, then you can make your own like this:
var uploadFile = function (type) {
var defer = $q.defer();
var file = $scope.fileObj[type];
//service to upload file
fileService.uploadDocument(file)
.success(function (data, status) {
console.log("uploaded successfully", data);
$scope.documentUploaded.push({
doc: {
fileName: data.name,
path: data.path
}
});
defer.resolve();
})
.error(function (data, status) {
defer.reject();
});
return defer.promise;
}
Related
In my angularjs app I have the following code on button click:
if (!$scope.isChecked) {
$scope.getExistingName($scope.userName).then(function (data) {
$scope.userName = data;
});
}
//some processing code here then another promise
myService.save($scope.userName,otherparams).then(function (res) {
//route to page
}, function (err) {
});
The issue here is if $scope.isChecked is false, it goes inside the promise and since it takes time to resolve it comes out and goes to next line of code. Because of this $scope.userName is not updated and uses old values instead of the updated value returned.
Whats the best way to handle this?
You can use $q. First you have to inject $q in your angular controller.
//Create empty promise
var promise;
if (!$scope.isChecked) {
promise = $scope.getExistingName($scope.userName).then(function (data) {
$scope.userName = data;
});
}
// Wait or not for your promise result, depending if promise is undefined or not.
$q.all([promise]).then(function () {
//some processing code here then another promise
myService.save($scope.userName,otherparams).then(function (res) {
//route to page
}, function (err) {
});
});
If the myService.save need to wait for the $scope.getExistingName promise just compute that operation inside the "then" statement.
if (!$scope.isChecked) {
$scope.getExistingName($scope.userName).then(function (data) {
$scope.userName = data;
myService.save($scope.userName,otherparams).then(function (res) {
//route to page
}, function (err) {
});
});
}
//some processing code here then another promise
I'm trying to use $q.all() to wait until a bunch of promises is resolved. For this purpose, i created a promises array and I pass it to the all() method, but this doesn't seem to work.
The promises array is filled with the promises returned by the $resource objects, that are created in each iteration, and I think that's the problem because the promises array is filled asynchronously.
I have come to this conclusion because the promise, array of promises, returned by the $q.all() method is always an empty array. It's like the $q.all() method doesn't wait for the array to get filled up. But I'm not sure if that is the problem.
I will really appreciate any help in this matter and, if it is not possible to achieve what I want with $ q.all(), i would like to see other ways to execute code after all the promises are resolved.
Here is the code I am currently using
var promisesArray = [];
var images, postObject;
files.readFile('images.txt')
.then(function (data) {
images= angular.fromJson(data);
images.forEach(function (image, idx) {
var deferred = $q.defer();
if (!image.sent) {
files.readFile(image.name)
.then(function (data) {
postObject = angular.fromJson(data);
$resource(EndPointsService.baseURL + "images").save(postObject, function(data) {
deferred.resolve(data);
if (data.status) {
image.sent= true;
}
},function(error){
console.log(error);
});
promisesArray.push(deferred.promise);
},function(error){
console.log(error);
});
}
});
$q.all(promisesArray).then(function (data) {
console.log(data);
files.writeFile("images.txt", images)
.then(function (data) {
console.log(data);
}, function (error) {
console.log(error);
});
});
},function(error){
console.log(error)
});
The .then method of a promise returns a new promise from data returned to it.
Create the promise array inside the .then method and return the $q.all promise to that .then method:
̶v̶a̶r̶ ̶p̶r̶o̶m̶i̶s̶e̶s̶A̶r̶r̶a̶y̶ ̶=̶ ̶[̶]̶;̶
var images, postObject;
var arrayPromise = files.readFile('images.txt')
.then(function (data) {
͟v͟a͟r͟ ͟p͟r͟o͟m͟i͟s͟e͟s͟A͟r͟r͟a͟y͟ ͟=͟ ͟[͟]͟;͟
images= angular.fromJson(data);
images.forEach(function (image, idx) {
̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
if (!image.sent) {
var promise = files.readFile(image.name)
.then(function (data) {
postObject = angular.fromJson(data);
var url = EndPointsService.baseURL + "images"
͟r͟e͟t͟u͟r͟n͟ $resource(url).save(postObject).$promise;
});
promisesArray.push(promise);
};
});
͟r͟e͟t͟u͟r͟n͟ $q.all(promisesArray);
});
arrayPromise.then(function (dataArray) {
console.log(dataArray);
//Process data here
});
I am trying to delete a post from a list. The delete function is performing by passing serially to a delete function showed below.
$scope.go = function(ref) {
$http.get("api/phone_recev.php?id="+ref)
.success(function (data) { });
}
After performing the function, I need to reload the http.get request which used for listing the list.
$http.get("api/phone_accept.php")
.then(function (response) { });
Once the function performed. The entire list will reload with new updated list. Is there any way to do this thing.
Try this
$scope.go = function(ref) {
$http.get("api/phone_recev.php?id="+ref)
.success(function (data) {
//on success of first function it will call
$http.get("api/phone_accept.php")
.then(function (response) {
});
});
}
function list_data() {
$http.get("api/phone_accept.php")
.then(function (response) {
console.log('listing');
});
}
$scope.go = function(ref) {
$http.get("api/phone_recev.php?id="+ref)
.success(function (data) {
// call function to do listing
list_data();
});
}
Like what #sudheesh Singanamalla says by calling the same http.get request again inside function resolved my problem.
$scope.go = function(ref) {
$http.get("api/phone_recev.php?id="+ref).success(function (data) {
//same function goes here will solve the problem.
});}
});
You can use $q - A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.
https://docs.angularjs.org/api/ng/service/$q
Inside some service.
app.factory('SomeService', function ($http, $q) {
return {
getData : function() {
// the $http API is based on the deferred/promise APIs exposed by the $q service
// so it returns a promise for us by default
return $http.get("api/phone_recev.php?id="+ref)
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
};
});
function somewhere in controller
var makePromiseWithData = function() {
// This service's function returns a promise, but we'll deal with that shortly
SomeService.getData()
// then() called when gets back
.then(function(data) {
// promise fulfilled
// something
}, function(error) {
// promise rejected, could log the error with: console.log('error', error);
//some code
});
};
I am trying to work through JS Promises in node.js and don't get the solution for passing promises between different function.
The task
For a main logic, I need to get a json object of items from a REST API. The API handling itself is located in a api.js file.
The request to the API inthere is made through the request-promise module. I have a private makeRequest function and public helper functions, like API.getItems().
The main logic in index.js needs to wait for the API function until it can be executed.
Questions
The promise passing kind of works, but I am not sure if this is more than a coincidence. Is it correct to return a Promise which returns the responses in makeRequest?
Do I really need all the promises to make the main logic work only after waiting for the items to be setup? Is there a simpler way?
I still need to figure out, how to best handle errors from a) the makeRequest and b) the getItems functions. What's the best practice with Promises therefor? Passing Error objects?
Here is the Code that I came up with right now:
// index.js
var API = require('./lib/api');
var items;
function mainLogic() {
if (items instanceof Error) {
console.log("No items present. Stopping main logic.");
return;
}
// ... do something with items
}
API.getItems().then(function (response) {
if (response) {
console.log(response);
items = response;
mainLogic();
}
}, function (err) {
console.log(err);
});
api.js
// ./lib/api.js
var request = require('request-promise');
// constructor
var API = function () {
var api = this;
api.endpoint = "https://api.example.com/v1";
//...
};
API.prototype.getItems = function () {
var api = this;
var endpoint = '/items';
return new Promise(function (resolve, reject) {
var request = makeRequest(api, endpoint).then(function (response) {
if (200 === response.statusCode) {
resolve(response.body.items);
}
}, function (err) {
reject(false);
});
});
};
function makeRequest(api, endpoint) {
var url = api.endpoint + endpoint;
var options = {
method: 'GET',
uri: url,
body: {},
headers: {},
simple: false,
resolveWithFullResponse: true,
json: true
};
return request(options)
.then(function (response) {
console.log(response.body);
return response;
})
.catch(function (err) {
return Error(err);
});
}
module.exports = new API();
Some more background:
At first I started to make API request with the request module, that works with callbacks. Since these were called async, the items never made it to the main logic and I used to handle it with Promises.
You are missing two things here:
That you can chain promises directly and
the way promise error handling works.
You can change the return statement in makeRequest() to:
return request(options);
Since makeRequest() returns a promise, you can reuse it in getItems() and you don't have to create a new promise explicitly. The .then() function already does this for you:
return makeRequest(api, endpoint)
.then(function (response) {
if (200 === response.statusCode) {
return response.body.items;
}
else {
// throw an exception or call Promise.reject() with a proper error
}
});
If the promise returned by makeRequest() was rejected and you don't handle rejection -- like in the above code --, the promise returned by .then() will also be rejected. You can compare the behaviour to exceptions. If you don't catch one, it bubbles up the callstack.
Finally, in index.js you should use getItems() like this:
API.getItems().then(function (response) {
// Here you are sure that everything worked. No additional checks required.
// Whatever you want to do with the response, do it here.
// Don't assign response to another variable outside of this scope.
// If processing the response is complex, rather pass it to another
// function directly.
}, function (err) {
// handle the error
});
I recommend this blog post to better understand the concept of promises:
https://blog.domenic.me/youre-missing-the-point-of-promises/
I am developing a file reading service that look like this:
angular.factory('fileService', fileService);
function fileService($cordovaFile){
var service = {
readFile: readFile
};
return service;
///////////////
function readFile(path, file){
$cordovaFile.readAsText(path, file)
.then(function (success) {
console.log("read file success");
console.log(success);
return success;
}, function (error) {
alert("Fail to read file:"+error);
console.log("Fail to read file");
console.log(error);
return false;
});
}
}
And then using it like this:
var data = fileService.readFile(cordova.file.dataDirectory,filename);
console.log(data) //return undefined
The problem is it fail to return the data. How can I get the data return back?
Your problem is that you are not actually returning any result from the readFile function. You are returning data from your callback functions but if you come to think of it...that result is returned to the function readFile itself and it stays inside that function. What you would want to do is return the whole result of the function readFile and then resolve the promise in the controller where you use it. Here is the code:
angular.factory('fileService', fileService);
function fileService($cordovaFile){
var service = {
readFile: readFile
};
return service;
function readFile(path, file){
return $cordovaFile.readAsText(path, file);
}
}
And then you use it like this:
var data = fileService.readFile(cordova.file.dataDirectory,filename);
data.then(function (success) {
// Do whatever you need to do with the result
}, function (error) {
/// Handle errors
});
In general, when you use services to implement some kind of functionality that uses promises and returns result, you should always return the promise object which can be than resolved anywhere that it is needed.
I highly recommend that you read this great explanation for promise objects.
Your function readFile returns nothing, so, firstly you should be returning the promise:
function readFile(path, file) {
return
$cordovaFile.readAsText(path, file).then(function (success) {
console.log('Read file success');
console.log(success);
return success;
}, function (error) {
alert('Fail to read file: ' + error);
console.log('Fail to read file');
console.log(error);
return false;
});
}
And then, if you try to use it the way you were, you'll not get undefined anymore, you'll get a promise.
But since it's an async method, you'll get that promise still pending, and you probably don't want that, since you'll need the promise's fulfilled value. So, you should use it like this:
fileService.readFile(cordova.file.dataDirectory, filename).then(function(data) {
// use data here
});