How to return promise from .then - javascript

I want to be able to chain promises in order to make code synchronous. My problem is that depending on result of first $http request I could either be wanting to send another or not.
In case if I choose not to send another $http request I don't need my second then() to do anything. But since my second then() doesn't know about all this and it's hanging there anyway so I figured I need to return from first then some fake dummy promise. But I would also like to recognize this case in second then() . I came up with returning $q.when('some value') from first case. Here is the code:
$http.get(url, params)
.then(function(res) {
res = res.data;
if (res.status == 'ok' && res.rows.length > 0) {
$scope.roomTypes = res.rows;
return $q.when({ isDummy: true }); //in this case I don't need to send another request
} else if (res.rows.length === 0 && $scope.request.roomType) {
return $http.get(url2, params2); //make second request and return then`able promise
}
}, function(res) {
throw 'Error';
})
.then(function(res) {
res = res.data;
if (res.status == 'ok') {
var roomType = {
room_type: res.roomType.id,
description: res.roomType.description
};
$scope.roomTypes.push(roomType);
} else if (res.isDummy) {
//ok that's our dummy promise
} else {
//format of response unexpected it means something went wrong
throw "error";
}
}, funcrtion(res) {
throw "some Error";
})
.catch(function(res) {...})
.finally(function() {...});
The thing is I want to see value with which promise was resolved ({isDummy: true}), but how do I do that? I get undefined in my res parameter.

res will be undefined here
.then(function(res) {
res = res.data;
...
because there's no data property on {isDummy: true} object.

I think the basic issue here is confusing promises with promise handlers. The success handlers should return a value, not another promise. When you are in a promise success handler you are 'wrapped' by the promise mechanism which takes you returned value and passes it on to the next handler. This means your second promise does not see the initial response but what the first promise returned.
The value is processed as it goes along unless you pass it as is.
For example
This all comes to that your line
return $q.when({isDummy: true});
Should be
return {isDummy: true};
The problem is the other case, where you want to continue to a next query. I would probably do one of the following:
1. Start in the first promise the handling (with the related logic from the first handler).
2. Pass on url2 and params - return({url: url2, params: params}) and handle them in the second promise.
Note the promise chanins can even break in the middle, if any of the handlers rejects, following success handlers will not be called, here is a simple example (make sure you open your devtools console to see the log).

Try to return any object except promise or deferred :) And its value will be passed to then. Like this:
return { isDummy: true };
Example code: https://jsfiddle.net/817pwvus/
From jQuery when documentation:
If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately. The doneCallbacks are passed the original argument.

If you want code sync, you can always write a long code block in the first then.
if you want to chain promise (Post:url1)->(Post:url2) and so on:
1.The return is useless.
2. Let's assume you have 2 $http promises you want to chain, both from a service called $users, for example, and they called GetUserAge and GetRelevantBars and the second query is based on the first one's results.
angular
.module("moduleA")
.controller("exmapleCtrl",exampleCtrl);
exampleCtrl.$injector=["$users"];
function exampleCtrl($users){
var vm=this;
vm.query = $users.GetUserAge().then( /*OnSuccess*/ GetUserAgeCB)
//Callback of the GetUserAgeCB;
function GetUserAgeCB(result){
$users.GetRelevantBars().then( /*OnSuccess*/ GetRelevantBarsCB);
/*continuation of CallBack code*/
}
//Callback of the GetRelevantBarsCB;
function GetRelevantBarsCB(result){
/*CallBack code*/
}
}
hope this is understandable..

Instead of returning a dummy value and ignoring that explictly, you rather should nest and attach the second handler only to the promise that needs it:
$http.get(url, params)
.then(function(res) {
var data = res.data;
if (data.status == 'ok' && data.rows.length > 0) {
$scope.roomTypes = data.rows;
return; // do nothing
} else if (res.rows.length === 0 && $scope.request.roomType) {
return $http.get(url2, params2)
.then(function(res) {
var data = res.data;
if (data.status == 'ok')
$scope.roomTypes.push({
room_type: data.roomType.id,
description: data.roomType.description
});
else
throw "error"; //format of response unexpected it means something went wrong
});
}
})
.catch(function(res) {…})
.finally(function() {…});

Related

What happens if i don't resolve a Promise? [duplicate]

I have a scenario where I am returning a promise.
The promise is basically triggered by an ajax request.
On rejecting the promise it shows an error dialog that there is a server error.
What I want to do is when the response code is 401, I neither want to resolve the promise nor reject it (because it already shows the error dialog). I want to simply redirect to the login page.
My code looks something like this:
function makeRequest(ur, params) {
return new Promise(function (resolve, reject) {
fetch(url, params).then((response) => {
let status = response.status;
if (status >= 200 && status < 300) {
response.json().then((data) => {
resolve(data);
});
} else {
if (status === 401) {
redirectToLoginPage();
} else {
response.json().then((error) => {
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
reject({ status, error });
});
}
}
});
});
}
As you can see, if the status is 401, I am redirecting to the login page. The promise is neither resolved nor rejected.
Is this code OK, or is there any better way to accomplish this?
A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object. The promise will still get garbage collected (even if still pending) if no code keeps a reference to the promise.
The real consequence here is what does that mean to the consumer of the promise if its state is never changed? Any .then() or .catch() listeners for resolve or reject transitions will never get called. Most code that uses promises expects them to resolve or reject at some point in the future (that's why promises are used in the first place). If they don't, then that code generally never gets to finish its work.
Or if code is using await on the promise instead of .then(), then that function will just remain suspended forever on that await. The rest of the function will be dead code and will never execute.
It's possible that you could have some other code that finishes the work for that task and the promise is just abandoned without ever doing its thing. There's no internal problem in Javascript if you do it that way, but it is not how promises were designed to work and is generally not how the consumer of promises expect them to work.
As you can see if the status is 401, I am redirecting to login page.
Promise is neither resolved nor rejected.
Is this code OK? Or is there any better way to accomplish this.
In this particular case, it's all OK and a redirect is a somewhat special and unique case. A redirect to a new browser page will completely clear the current page state (including all Javascript state) so it's perfectly fine to take a shortcut with the redirect and just leave other things unresolved. The system will completely reinitialize your Javascript state when the new page starts to load so any promises that were still pending will get cleaned up.
I think the "what happens if we don't resolve reject" has been answered fine - it's your choice whether to add a .then or a .catch.
However, Is this code OK? Or is there any better way to accomplish this. I would say there are two things:
You are wrapping a Promise in new Promise when it is not necessary and the fetch call can fail, you should act on that so that your calling method doesn't sit and wait for a Promise which will never be resolved.
Here's an example (I think this should work for your business logic, not 100% sure):
const constants = {
SERVER_ERROR: "500 Server Error"
};
function makeRequest(url,params) {
// fetch already returns a Promise itself
return fetch(url,params)
.then((response) => {
let status = response.status;
// If status is forbidden, redirect to Login & return nothing,
// indicating the end of the Promise chain
if(status === 401) {
redirectToLoginPage();
return;
}
// If status is success, return a JSON Promise
if(status >= 200 && status < 300) {
return response.json();
}
// If status is a failure, get the JSON Promise,
// map the message & status, then Reject the promise
return response.json()
.then(json => {
if (!json.message) {
json.message = constants.SERVER_ERROR;
}
return Promise.reject({status, error: json.message});
})
});
}
// This can now be used as:
makeRequest("http://example", {})
.then(json => {
if(typeof json === "undefined") {
// Redirect request occurred
}
console.log("Success:", json);
})
.catch(error => {
console.log("Error:", error.status, error.message);
})
By contrast, calling your code using:
makeRequest("http://example", {})
.then(info => console.log("info", info))
.catch(err => console.log("error", err));
Will not log anything because the call to http://example will fail, but the catch handler will never execute.
As others stated it's true that it's not really an issue if you don't resolve/reject a promise. Anyway I would solve your problem a bit different:
function makeRequest(ur,params) {
return new Promise(function(resolve,reject) {
fetch(url,params)
.then((response) => {
let status = response.status;
if (status >= 200 && status < 300) {
response.json().then((data) => {
resolve(data);
})
}
else {
reject(response);
}
})
});
}
makeRequest().then(function success(data) {
//...
}, function error(response) {
if (response.status === 401) {
redirectToLoginPage();
}
else {
response.json().then((error) => {
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
//do sth. with error
});
}
});
That means I would reject every bad response state and then handle this in your error handler of your makeRequest.
It works and isn't really a problem, except when a caller of makeRequest expects of promise to fulfil. So, you're breaking the contract there.
Instead, you could defer the promise, or (in this case) reject with status code/error.
The ECMAScript spec explains the purpose of promises and new Promise():
A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.
25.6.3.1 Promise ( executor )
NOTE The executor argument must be a function object. It is called for initiating and reporting completion of the possibly deferred action represented by this Promise object.
You should use promises to obtain future values. Furthermore, to keep your code concise and direct, you should only use promises to obtain future values, and not to do other things.
Since you’ve also mixed program control flow (redirection logic) into your promise’s “executor” logic, your promise is no longer “a placeholder for the results of a computation;” rather, it’s now a little JavaScript program masquerading as a promise.
So, instead of wrapping this JavaScript program inside a new Promise(), I recommend just writing it like a normal JavaScript program:
async function makeRequest(url, params) {
let response = await fetch(url, params);
let { status } = response;
if (status >= 200 && status < 300) {
let data = await response.json();
successLogic(data);
} else if (status === 401) {
redirectToLoginPage();
} else {
let error = await response.json()
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
errorLogic({ status, error });
}
}

How to correctly handle promise from multiple api calls?

I have an endpoint where I make multiple of the same call but with different id in the URL. It seems to be executing API calls however it is not triggering my alert notification.
How can I correctly handle this in case it fails?
Is there a cleaner/more efficient approach?
let myArray = [1,2,3,4]
myArray.forEach(i => {
let update = request.update(`view/${i}`);
return update;
});
if(update)
{
alert("Success")
} else {
alert("failed")
}
Assuming request.update() is returning a Promise, you can use Promises.all(). You should read the docs to understand the behavior of this. If even one request fails, your function will fail, even if the other requests successfully updated.
//
let myArray = [1,2,3,4]
//a place to store the promises while we wait
let requests = [];
//
myArray.forEach(i => {
//save the promise in the array
requests.push( request.update(`view/${i}`) );
});
//wait for all requests to finish
Promise.all( requests )
.then(results => alert('Success'))
.catch(e => alert("failed"));
A way of dealing with a Promise is to use the .then() function which will execute callback functions to deal with the result of each of your requests.
You should use this fonction like this :
//promise.then(onFulfilled[, onRejected]);
let myArray = [1,2,3,4]
myArray.forEach(i => {
request.update(`view/${i}`).then(response => {
//Fulfilment
},reason=>{
//Rejection
});
});
This should be enough for your problem.
Sometimes I prefer keeping it "simple" by managing the result of the promise in the first callback only, this implies you have control of the response you are receiving and can identify rejection other way :
let myArray = [1,2,3,4]
myArray.forEach(i => {
request.update(`view/${i}`).then(response=>{
if(response){
//If I control the response I can identify the status of the request
const data = JSON.parse(response);
switch(data.status){
case "error":
//Do stuff
break;
case "unknown":
//Do stuff
break;
case "valid":
//Do stuff
break;
}
}else{
//This means no response was received, it is different from Promise rejection
//it may have been caused by network issues.
//You can trigger some error from here or do what you want
}
});
//This way I treat the Promise in one callback instead of two
});
Documentation for .then() is available here.
Hope it helped someone.

JS: Complex Promise chaining

I'm faced with a small issue when trying to chain complex function calls with Promises and callbacks.
I have a main function, which calls subroutines. In these routines API calls are made.
For Example:
function handle(){
new Promise(function(resolve, reject){
let result = doAPICall1()
if (result === true) resolve(true);
reject(JSON.stringify(result))
}).then(function(){
let result = doAPICall2()
if (result === true) return true
throw new Error(JSON.stringify(result))
}).catch(error){
console.error(JSON.stringify(error))
}
}
function doAPICall1(){
axios.get('...').then(function(){
return true
}).catch(function(error){
return error
})
}
function doAPICall2(){
axios.get('...').then(function(){
return true
}).catch(function(error){
return error
})
}
But when I execute this example, doAPICall2 will be executed, while doAPICall1 is still running.
It only occures when long running calls are made.
Does anyone can give me a hint? Thank you!
You're overdoing manually a lot of things that Promises already do for you:
axios.get already returns a Promise, so there is no point in return a the response when it resolves and return a false when it rejects. A catch handler at the end of a Promise chain already handles all errors that may arise during the chain, so you don't need to catch every Promise.
I would do something like:
function doAPICall1(){
return axios.get('...');
}
function doAPICall2(){
return axios.get('...');
}
function handle(){
// in case you would use the api calls results.
let firstResult = null;
let secondResult = null;
return doAPICall1()
.then(res => {firstResult = res})
.then(() => doAPICall2())
.then(res => {
secondResult = res;
return []
})
}
I guess you will use the Api calls results for something. With the code above, you could consume the handle() function like follows:
function someSortOfController(){
handle().then(results => {
console.log(results[0]); // first api call result
console.log(results[1]); // second api call result
})
.catch(err => {
// here you will find any error, either it fires from the first api call or from the second.
// there is *almomst* no point on catch before
console.log(err);
})
}
There, you will access any error, either it came from the first api call or the second. (And, due to how Promises work, if the first call fails, the second won't fire).
For more fine grained error control, you may want to catch after every Promise so you can add some extra logs, like:
function doAPICall1(){
return axios.get('...')
.catch(err => {
console.log('the error came from the first call');
throw err;
});
}
function doAPICall2(){
return axios.get('...')
.catch(err => {
console.log('the error came from the second call');
throw err;
});
}
Now, if the first api call fails, everything will work as before (since you're throwing the error again in the catch), but you have more control over error handling (maybe the error returning from API calls is not clear at all and you want this kind of control mechanism).
 Disclaimer
This answer doesn't answer why your code acts like it does. However, there are so much things wrong in your code, so I think providing you with an example about using Promises is more valuable.
Don't worry and take some time to understand Promises better. In the example code below, doAPICall function return a Promise which resolves to a value, not the value itself.
function handle() {
doAPICall().then(result => {
//do something with the result
}).catch(error => {
//catch failed API call
console.error(error)
})
}
doAPICall() {
// this returns a Promise
return axios.get(...)
}

What happens if you don't resolve or reject a promise?

I have a scenario where I am returning a promise.
The promise is basically triggered by an ajax request.
On rejecting the promise it shows an error dialog that there is a server error.
What I want to do is when the response code is 401, I neither want to resolve the promise nor reject it (because it already shows the error dialog). I want to simply redirect to the login page.
My code looks something like this:
function makeRequest(ur, params) {
return new Promise(function (resolve, reject) {
fetch(url, params).then((response) => {
let status = response.status;
if (status >= 200 && status < 300) {
response.json().then((data) => {
resolve(data);
});
} else {
if (status === 401) {
redirectToLoginPage();
} else {
response.json().then((error) => {
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
reject({ status, error });
});
}
}
});
});
}
As you can see, if the status is 401, I am redirecting to the login page. The promise is neither resolved nor rejected.
Is this code OK, or is there any better way to accomplish this?
A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object. The promise will still get garbage collected (even if still pending) if no code keeps a reference to the promise.
The real consequence here is what does that mean to the consumer of the promise if its state is never changed? Any .then() or .catch() listeners for resolve or reject transitions will never get called. Most code that uses promises expects them to resolve or reject at some point in the future (that's why promises are used in the first place). If they don't, then that code generally never gets to finish its work.
Or if code is using await on the promise instead of .then(), then that function will just remain suspended forever on that await. The rest of the function will be dead code and will never execute.
It's possible that you could have some other code that finishes the work for that task and the promise is just abandoned without ever doing its thing. There's no internal problem in Javascript if you do it that way, but it is not how promises were designed to work and is generally not how the consumer of promises expect them to work.
As you can see if the status is 401, I am redirecting to login page.
Promise is neither resolved nor rejected.
Is this code OK? Or is there any better way to accomplish this.
In this particular case, it's all OK and a redirect is a somewhat special and unique case. A redirect to a new browser page will completely clear the current page state (including all Javascript state) so it's perfectly fine to take a shortcut with the redirect and just leave other things unresolved. The system will completely reinitialize your Javascript state when the new page starts to load so any promises that were still pending will get cleaned up.
I think the "what happens if we don't resolve reject" has been answered fine - it's your choice whether to add a .then or a .catch.
However, Is this code OK? Or is there any better way to accomplish this. I would say there are two things:
You are wrapping a Promise in new Promise when it is not necessary and the fetch call can fail, you should act on that so that your calling method doesn't sit and wait for a Promise which will never be resolved.
Here's an example (I think this should work for your business logic, not 100% sure):
const constants = {
SERVER_ERROR: "500 Server Error"
};
function makeRequest(url,params) {
// fetch already returns a Promise itself
return fetch(url,params)
.then((response) => {
let status = response.status;
// If status is forbidden, redirect to Login & return nothing,
// indicating the end of the Promise chain
if(status === 401) {
redirectToLoginPage();
return;
}
// If status is success, return a JSON Promise
if(status >= 200 && status < 300) {
return response.json();
}
// If status is a failure, get the JSON Promise,
// map the message & status, then Reject the promise
return response.json()
.then(json => {
if (!json.message) {
json.message = constants.SERVER_ERROR;
}
return Promise.reject({status, error: json.message});
})
});
}
// This can now be used as:
makeRequest("http://example", {})
.then(json => {
if(typeof json === "undefined") {
// Redirect request occurred
}
console.log("Success:", json);
})
.catch(error => {
console.log("Error:", error.status, error.message);
})
By contrast, calling your code using:
makeRequest("http://example", {})
.then(info => console.log("info", info))
.catch(err => console.log("error", err));
Will not log anything because the call to http://example will fail, but the catch handler will never execute.
As others stated it's true that it's not really an issue if you don't resolve/reject a promise. Anyway I would solve your problem a bit different:
function makeRequest(ur,params) {
return new Promise(function(resolve,reject) {
fetch(url,params)
.then((response) => {
let status = response.status;
if (status >= 200 && status < 300) {
response.json().then((data) => {
resolve(data);
})
}
else {
reject(response);
}
})
});
}
makeRequest().then(function success(data) {
//...
}, function error(response) {
if (response.status === 401) {
redirectToLoginPage();
}
else {
response.json().then((error) => {
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
//do sth. with error
});
}
});
That means I would reject every bad response state and then handle this in your error handler of your makeRequest.
It works and isn't really a problem, except when a caller of makeRequest expects of promise to fulfil. So, you're breaking the contract there.
Instead, you could defer the promise, or (in this case) reject with status code/error.
The ECMAScript spec explains the purpose of promises and new Promise():
A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.
25.6.3.1 Promise ( executor )
NOTE The executor argument must be a function object. It is called for initiating and reporting completion of the possibly deferred action represented by this Promise object.
You should use promises to obtain future values. Furthermore, to keep your code concise and direct, you should only use promises to obtain future values, and not to do other things.
Since you’ve also mixed program control flow (redirection logic) into your promise’s “executor” logic, your promise is no longer “a placeholder for the results of a computation;” rather, it’s now a little JavaScript program masquerading as a promise.
So, instead of wrapping this JavaScript program inside a new Promise(), I recommend just writing it like a normal JavaScript program:
async function makeRequest(url, params) {
let response = await fetch(url, params);
let { status } = response;
if (status >= 200 && status < 300) {
let data = await response.json();
successLogic(data);
} else if (status === 401) {
redirectToLoginPage();
} else {
let error = await response.json()
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
errorLogic({ status, error });
}
}

How to make the later Promises wait for the first Promise to finish in bluebird?

I'm trying to chain Promises. Here's the code
crawler.cache(url).then(function (cRes) {
console.log('get from cache');
if(cRes) {
return Promise.resolve(JSON.parse(cRes));
} else {
console.log('no cache');
crawler.db(url).then(function (result) {
console.log('get from db');
return Promise.resolve(JSON.parse(result));
});
}
}).then(function fetch(someResult) {
console.log('fetch data from' + someResult);
});
What I'm hoping is that it would look into the cache first if it couldn't find then it should look in to db. And then pass the result to the last then which to fetch the result.
But here's what printing from my console.
get from cache
no cache
fetch data from null
get from db
First it couldn't find anything in the cache then it's trying to fetch from the database but it didn't wait until getting from the db is done it went on to fetch data.
How do I solve this problem when the last then has to wait for everything above it to finish to get the result then it can do the next operation?
You can just return the promise inside the then continuation, this will cause the parent promise to wait until the returned promise is fulfilled and adopt it's value.
There is also no need to use the Promise.resolve method, you can just return the value directly.
crawler.cache(url).then(function (cRes) {
if (cRes) {
console.log('cache result');
return JSON.parse(cRes);
} else {
console.log('no cache');
return crawler.db(url).then(function (result) {
return JSON.parse(result);
});
}
}).then(function fetch(someResult) {
console.log('fetch data from' + someResult);
});
Bonus:
If you are storing your cache in memory. you probably don't need to return a promise from your crawler.cache function.
OT: I'd recomend you a slightly different approach. Use the rejection-path of the promises to communicate that a Value is not available/couldn't be resolved or provided.
This way it would be more intuitive wether a (possibly falsy) value is provided or, wether we have to resolve that from a different source like the db.
Sth. like (pseudocode):
crawler.cache = function(url){
//you will have to adapt this part to your structure.
//but you get the idea?
return new Promise(function(resolve, reject){
if(url in _cache){
resolve( _cache[url] );
}else{
//you can simply reject() without a reason,
//or you can return an Error-Object, or some message, or whatever ...
reject({ message: "no cache for " + url });
}
});
}
//try to access the value from the cache
crawler.cache(url)
//if the cache fails (to provide you a value),
//try to resolve the value from the db
.catch(() => crawler.db(url).then(saveToCache))
//parse the result, wether it is from the cache or the db
//maybe you want to add a second argument to catch the case where the db also fails?
.then(str => JSON.parse(str));
//maybe you want to add a catch here,
//in case JSON.parse is provided sth false, like a damaged string?

Categories

Resources