How to correctly handle promise from multiple api calls? - javascript

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.

Related

Question about asynchronous JavaScript with Promise

Here I have a function that takes an array of string that contains the user names of github accounts. And this function is going to return an array of user data after resolving. There should be one fetch request per user. and requests shouldn’t wait for each other. So that the data arrives as soon as possible. If there’s no such user, the function should return null in the resulting array.
An example for the input would be ["iliakan", "remy", "no.such.users"], and the expected returned promise after resolving would give us [null, Object, Object], Object being the data that contained info about a user.
Here is my attempt to solve this question.
function getUsers(names) {
return new Promise(resolve => {
const array = [];
const url = "https://api.github.com/users/";
const requests = names.map(name => {
const endpoint = `${url}${name}`;
return fetch(endpoint);
});
Promise.all(requests).then(reponses => {
reponses.forEach(response => {
if (response.status === 200) {
response.json().then(data => {
array.push(data);
});
} else {
array.push(null);
}
});
resolve(array);
});
});
}
It does work, i.e. returning an array [null, Object, Object]. And I thought it fulfilled the requirements I stated above. However, after looking at it closely, I felt like I couldn't fully make sense of it.
My question is, look at where we resolve this array, it resolved immediately after the forEach loop. One thing I don't understand is, why does it contain all three items when some of the items are pushed into it asynchronously after the json() is finished. what I mean is, in the case where response.status === 200, the array is pushed with the data resolved from json(), and I would assume this json() operation should take some time. Since we didn't resolve the array after json() operation is finished, how come we still ended up with all data resolved from json()?
Promise.all(requests).then(reponses => {
reponses.forEach(response => {
if (response.status === 200) {
response.json().then(data => {
array.push(data); <--- this should take some time
});
} else {
array.push(null);
}
});
resolve(array); <--- resolve the array immediately after the `forEach` loop
});
});
It looks to me like the array we get should only have one null in it since at the time it is revolved, the .json() should not be finished
You're right, the result is pushed later into the array.
Try to execute this:
const test = await getUsers(['Guerric-P']);
console.log(test.length);
You'll notice it displays 0. Before the result is pushed into the array, its length is 0. You probably think it works because you click on the array in the console, after the result has arrived.
You should do something like this:
function getUsers(names) {
const array = [];
const url = "https://api.github.com/users/";
const requests = names.map(name => {
const endpoint = `${url}${name}`;
return fetch(endpoint);
});
return Promise.all(requests).then(responses => Promise.all(responses.map(x => x.status === 200 ? x.json() : null)));
};
You should avoid using the Promise constructor directly. Here, we don't need to use it at all.
const url = "https://api.github.com/users/";
const getUsers = names =>
Promise.all(names.map(name =>
fetch(url + name).then(response =>
response.status === 200 ? response.json() : null)));
getUsers(["iliakan", "remy", "no.such.users"]).then(console.log);
The Promise constructor should only be used when you're creating new kinds of asynchronous tasks. In this case, you don't need to use the Promise constructor because fetch already returns a promise.
You also don't need to maintain an array and push to it because Promise.all resolves to an array. Finally, you don't need to map over the result of Promise.all. You can transform the promises returned by fetch.
The thing is that because json() operation is really quick, especially if response data is small in size it just has the time to execute. Second of all as objects in JavaScript passed by reference and not by value and Array is a object in JavaScript, independently of execution time it'll still push that data to the array even after it was resolved.

Determine if function is a jQuery promise

Suppose I have a page loader that can run a plain function, or a jquery AJAX request. I only want to move to the next step if the AJAX request was successful (ie done) and show an error if it wasn't (ie fail).
function runStep(stepText, functionToCall){
this.setStepText(stepText);
// call function
let result = functionToCall();
// if the function is jquery, wait for the result
if(result && typeof result.then === 'function'){
let self = this;
result.done(function(){
self.goToNextStep();
}).fail(function(){
self.showFailureMsg();
});
}
// if its a plain old function go to the next step
else {
this.goToNextStep();
}
}
What I don't get is; at the point I call done or faile, I've already run the jQuery AJAX request. So is it not too late to attach these handlers?
The nice thing about Promises is that it doesn't matter when you attach. Once they finalize, the state is constant.
In this way you can pass around a resolved or rejected Promise throughout the lifetime of your app and late listeners will still be called.
const pg = Promise.resolve("foo");
const pb = Promise.reject("bar");
pg.then(v => console.log(v));
pb.catch(err => console.error(err));
Since jqXHR Objects (which is what $.ajax() returns) implement the same interface as Promise, you can also attach whenever you want as well.
const d = $.Deferred();
const dpr = d.promise();
d.resolve("foo");
dpr.then(v => console.log(v));
setTimeout(() => {
console.log("Even 3 seconds later it's still foo");
dpr.then(v => console.log(v));
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Consider this concrete example that uses a real XHR:
const post = $.ajax("https://jsonplaceholder.typicode.com/posts/1");
post.then(p => {
// We are in the callback of the request
// so we know that it is complete
console.log(p.title);
// Let's add another callback when we *think*
// it should be too late
post.then(latep => {
// Still possible
console.log(p.title)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Node chain of promises and code readability

I'm trying to send several request/responses from a node server, and because they are async, I had to dive into and start learning promises. Im using bluebird and node as well as request to send requests.
Im looking to establish a certificate chain, and my server is acting trusted third party. I have the following
function send_certificates (addr) {
return send_csr_request(addr)
.then(function(csr) {
return new Promise(function(resolve,reject) {
resolve(sign_device_cert(csr))}
)}).then(function(signed_cert) {
return new Promise(function(resolve,reject) {
//another resolve here?
resolve(send_cert(signed_cert));
})
});
}
Ideally I would like to slap on another request to this "promise-chain", something like resolve(send_cert(caroot_cert))
and just generally be able to modify this chain of reqeust/responses a bit better. I feel like there is a lot of boilerplate code just to call these methods. Is there any other, more manageable and readable way to do this?
Also I'm not sure if I need to promisify all these methods? If, say, sign_device_cert returns a Promise, how do I chain it with .then() calls?
EDIT
Here is my function that sends off a request..
function send_ca_cert(cert) {
const url_string = "http://myaddress.com";
var request_options = {
url : url_string,
proxy : my_proxy,
body: pki.certificateToPem(cert),
headers: { "someHeader : "somevalue"}
};
return new Promise((resolve,reject) => {
request.postAsync(request_options, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Sent off ca cert" );
resolve();
}
reject();
});
});
}
When I call then(send_cert).then(send_ca_cert) i get the prints
Sent off ca cert
Sent off cert
How come they don't respect the Promises?
You don't have to wrap promises in promises. Do just
function send_certificates (addr) {
return send_csr_request(addr)
.then(sign_device_cert)
.then(send_cert);
}
This should work in your case (at least if your code works).
Sometimes, you can't just pass the original function because it needs different arguments (or a different context). In those cases you still can avoid creating a new promise:
return functionReturningAPromise()
.then(otherFunctionReturningAPromise) // takes as parameter the result of the previous one
.then(function(someValue){
return yetAnotherFunctionReturningAPromise(22, someValue);
});
You can write code in this fashion that will increase the code readability.
let promise = someAsyncFunction();
promise = promise.then((data) => { // here data is value if returned by function
return someAnotherAsyncCall();
});
promise = promise.then((data) => {// here data is value if returned by the previous function //}
return someAnotherAsyncCall();
});
// Similarly you can carry on!
// Don't forget to use arrow function they also help to increase the code readability and must use return statement at the end of promises to avoid promise chain break;

JS Promise - instantly retrieve some data from a function that returns a Promise

Can anyone recommend a pattern for instantly retrieving data from a function that returns a Promise?
My (simplified) example is an AJAX preloader:
loadPage("index.html").then(displayPage);
If this is downloading a large page, I want to be able to check what's happening and perhaps cancel the process with an XHR abort() at a later stage.
My loadPage function used to (before Promises) return an id that let me do this later:
var loadPageId = loadPage("index.html",displayPage);
...
doSomething(loadPageId);
cancelLoadPage(loadPageId);
In my new Promise based version, I'd imagine that cancelLoadPage() would reject() the original loadPage() Promise.
I've considered a few options all of which I don't like. Is there a generally accepted method to achieve this?
Okay, let's address your bounty note first.
[Hopefully I'll be able to grant the points to someone who says more than "Don't use promises"... ]
Sorry, but the answer here is: "Don't use promises". ES6 Promises have three possible states (to you as a user): Pending, Resolved and Rejected (names may be slightly off).
There is no way for you to see "inside" of a promise to see what has been done and what hasn't - at least not with native ES6 promises. There was some limited work (in other frameworks) done on promise notifications, but those did not make it into the ES6 specification, so it would be unwise of you to use this even if you found an implementation for it.
A promise is meant to represent an asynchronous operation at some point in the future; standalone, it isn't fit for this purpose. What you want is probably more akin to an event publisher - and even that is asynchronous, not synchronous.
There is no safe way for you to synchronously get some value out of an asynchronous call, especially not in JavaScript. One of the main reasons for this is that a good API will, if it can be asynchronous, will always be asynchronous.
Consider the following example:
const promiseValue = Promise.resolve(5)
promiseValue.then((value) => console.log(value))
console.log('test')
Now, let's assume that this promise (because we know the value ahead of time) is resolved synchronously. What do you expect to see? You'd expect to see:
> 5
> test
However, what actually happens is this:
> test
> 5
This is because even though Promise.resolve() is a synchronous call that resolves an already-resolved Promise, then() will always be asynchronous; this is one of the guarantees of the specification and it is a very good guarantee because it makes code a lot easier to reason about - just imagine what would happen if you tried to mix synchronous and asynchronous promises.
This applies to all asynchronous calls, by the way: any action in JavaScript that could potentially be asynchronous will be asynchronous. As a result, there is no way for you do any kind of synchronous introspection in any API that JavaScript provides.
That's not to say you couldn't make some kind of wrapper around a request object, like this:
function makeRequest(url) {
const requestObject = new XMLHttpRequest()
const result = {
}
result.done = new Promise((resolve, reject) => {
requestObject.onreadystatechange = function() {
..
}
})
requestObject.open(url)
requestObject.send()
return requestObject
}
But this gets very messy, very quickly, and you still need to use some kind of asynchronous callback for this to work. This all falls down when you try and use Fetch. Also note that Promise cancellation is not currently a part of the spec. See here for more info on that particular bit.
TL:DR: synchronous introspection is not possible on any asynchronous operation in JavaScript and a Promise is not the way to go if you were to even attempt it. There is no way for you to synchronously display information about a request that is on-going, for example. In other languages, attempting to do this would require either blocking or a race condition.
Well. If using angular you can make use of the timeout parameter used by the $http service if you need to cancel and ongoing HTTP request.
Example in typescript:
interface ReturnObject {
cancelPromise: ng.IPromise;
httpPromise: ng.IHttpPromise;
}
#Service("moduleName", "aService")
class AService() {
constructor(private $http: ng.IHttpService
private $q: ng.IQService) { ; }
doSomethingAsynch(): ReturnObject {
var cancelPromise = this.$q.defer();
var httpPromise = this.$http.get("/blah", { timeout: cancelPromise.promise });
return { cancelPromise: cancelPromise, httpPromise: httpPromise };
}
}
#Controller("moduleName", "aController")
class AController {
constructor(aService: AService) {
var o = aService.doSomethingAsynch();
var timeout = setTimeout(() => {
o.cancelPromise.resolve();
}, 30 * 1000);
o.httpPromise.then((response) => {
clearTimeout(timeout);
// do code
}, (errorResponse) => {
// do code
});
}
}
Since this approach already returns an object with two promises the stretch to include any synchronous operation return data in that object is not far.
If you can describe what type of data you would want to return synchronously from such a method it would help to identify a pattern. Why can it not be another method that is called prior to or during your asynchronous operation?
You can kinda do this, but AFAIK it will require hacky workarounds. Note that exporting the resolve and reject methods is generally considered a promise anti-pattern (i.e. sign you shouldn't be using promises). See the bottom for something using setTimeout that may give you what you want without workarounds.
let xhrRequest = (path, data, method, success, fail) => {
const xhr = new XMLHttpRequest();
// could alternately be structured as polymorphic fns, YMMV
switch (method) {
case 'GET':
xhr.open('GET', path);
xhr.onload = () => {
if (xhr.status < 400 && xhr.status >= 200) {
success(xhr.responseText);
return null;
} else {
fail(new Error(`Server responded with a status of ${xhr.status}`));
return null;
}
};
xhr.onerror = () => {
fail(networkError);
return null;
}
xhr.send();
return null;
}
return xhr;
case 'POST':
// etc.
return xhr;
// and so on...
};
// can work with any function that can take success and fail callbacks
class CancellablePromise {
constructor (fn, ...params) {
this.promise = new Promise((res, rej) => {
this.resolve = res;
this.reject = rej;
fn(...params, this.resolve, this.reject);
return null;
});
}
};
let p = new CancellablePromise(xhrRequest, 'index.html', null, 'GET');
p.promise.then(loadPage).catch(handleError);
// times out after 2 seconds
setTimeout(() => { p.reject(new Error('timeout')) }, 2000);
// for an alternative version that simply tells the user when things
// are taking longer than expected, NOTE this can be done with vanilla
// promises:
let timeoutHandle = setTimeout(() => {
// don't use alert for real, but you get the idea
alert('Sorry its taking so long to load the page.');
}, 2000);
p.promise.then(() => clearTimeout(timeoutHandle));
Promises are beautiful. I don't think there is any reason that you can not handle this with promises. There are three ways that i can think of.
The simplest way to handle this is within the executer. If you would like to cancel the promise (like for instance because of timeout) you just define a timeout flag in the executer and turn it on with a setTimeout(_ => timeout = true, 5000) instruction and resolve or reject only if timeout is false. ie (!timeout && resolve(res) or !timeout && reject(err)) This way your promise indefinitely remains unresolved in case of a timeout and your onfulfillment and onreject functions at the then stage never gets called.
The second is very similar to the first but instead of keeping a flag you just invoke reject at the timeout with proper error description. And handle the rest at the then or catch stage.
However if you would like to carry the id of your asych operation to the sync world then you can also do it as follows;
In this case you have to promisify the async function yourself. Lets take an example. We have an async function to return the double of a number. This is the function
function doubleAsync(data,cb){
setTimeout(_ => cb(false, data*2),1000);
}
We would like to use promises. So normally we need a promisifier function which will take our async function and return another function which when run, takes our data and returns a promise. Right..? So here is the promisifier function;
function promisify(fun){
return (data) => new Promise((resolve,reject) => fun(data, (err,res) => err ? reject(err) : resolve(res)));
}
Lets se how they work together;
function promisify(fun){
return (data) => new Promise((resolve,reject) => fun(data, (err,res) => err ? reject(err) : resolve(res)));
}
function doubleAsync(data,cb){
setTimeout(_ => cb(false, data*2),1000);
}
var doubleWithPromise = promisify(doubleAsync);
doubleWithPromise(100).then(v => console.log("The asynchronously obtained result is: " + v));
So now you see our doubleWithPromise(data) function returns a promise and we chain a then stage to it and access the returned value.
But what you need is not only a promise but also the id of your asynch function. This is very simple. Your promisified function should return an object with two properties; a promise and an id. Lets see...
This time our async function will return a result randomly in 0-5 secs. We will obtain it's result.id synchronously along with the result.promise and use this id to cancel the promise if it fails to resolve within 2.5 secs. Any figure on console log Resolves in 2501 msecs or above will result nothing to happen and the promise is practically canceled.
function promisify(fun){
return function(data){
var result = {id:null, promise:null}; // template return object
result.promise = new Promise((resolve,reject) => result.id = fun(data, (err,res) => err ? reject(err) : resolve(res)));
return result;
};
}
function doubleAsync(data,cb){
var dur = ~~(Math.random()*5000); // return the double of the data within 0-5 seconds.
console.log("Resolve in " + dur + " msecs");
return setTimeout(_ => cb(false, data*2),dur);
}
var doubleWithPromise = promisify(doubleAsync),
promiseDataSet = doubleWithPromise(100);
setTimeout(_ => clearTimeout(promiseDataSet.id),2500); // give 2.5 seconds to the promise to resolve or cancel it.
promiseDataSet.promise
.then(v => console.log("The asynchronously obtained result is: " + v));
You can use fetch(), Response.body.getReader(), where when .read() is called returns a ReadableStream having a cancel method, which returns a Promise upon cancelling read of the stream.
// 58977 bytes of text, 59175 total bytes
var url = "https://gist.githubusercontent.com/anonymous/"
+ "2250b78a2ddc80a4de817bbf414b1704/raw/"
+ "4dc10dacc26045f5c48f6d74440213584202f2d2/lorem.txt";
var n = 10000;
var clicked = false;
var button = document.querySelector("button");
button.addEventListener("click", () => {clicked = true});
fetch(url)
.then(response => response.body.getReader())
.then(reader => {
var len = 0;
reader.read().then(function processData(result) {
if (result.done) {
// do stuff when `reader` is `closed`
return reader.closed.then(function() {
return "stream complete"
});
};
if (!clicked) {
len += result.value.byteLength;
}
// cancel stream if `button` clicked or
// to bytes processed is greater than 10000
if (clicked || len > n) {
return reader.cancel().then(function() {
return "read aborted at " + len + " bytes"
})
}
console.log("len:", len, "result value:", result.value);
return reader.read().then(processData)
})
.then(function(msg) {
alert(msg)
})
.catch(function(err) {
console.log("err", err)
})
});
<button>click to abort stream</button>
The method I am currently using is as follows:
var optionalReturnsObject = {};
functionThatReturnsPromise(dataToSend, optionalReturnsObject ).then(doStuffOnAsyncComplete);
console.log("Some instant data has been returned here:", optionalReturnsObject );
For me, the advantage of this is that another member of my team can use this in a simple way:
functionThatReturnsPromise(data).then(...);
And not need to worry about the returns object. An advanced user can see from the definitions what is going on.

How to return promise from .then

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() {…});

Categories

Resources