Reputation: 73
I am working on SOA project where I am writing a node js utility to get my things done. The utility starts with login to server using a SOA call then call a series of SOA call where each SOA call depends on the result of the previous call.
I have used promise-then
framework to achieve this. Below is my code:
const loginPromise = postRequest(req, headersObj, loginUrl, Constants.loginData);
const queryPromise = loginPromise.then(loginSuccess, loginFailure);
const searchPromise = queryPromise.then(handleSavedQuerySearchResponse, onFailure);
const createPromise = searchPromise.then(handleSearchSoaResponse, onFailure);
const updatePromise = createPromise.then(handleCreateObjectSoaResposne, onFailure);
const plantDataPromise = updatePromise.then(handleUpdateObjectSoaResponse, onFailure);
function postRequest(request: any, header: any, reqUrl: string, jsonData: any): Promise<any> {
return new Promise((resolve) => {
request.post({
headers: header,
url: reqUrl,
body: JSON.stringify(jsonData),
}, (err: any, resp: any, bodyParam: any) => {
resolve({error: err, response: resp, body: bodyParam});
});
});
}
On successful execution of the one SOA the next SOA gets executed from the callback
function. Everything works fine when there is no error scenario. But if the server is down or in any other failure scenario I want to get out of this promise-then
chain.
Currently on any error the flow gets to onFailure
method but after its execution it gives the control to next promise in the chain with null
as input for that method.
I want to get out of the promise-then chain whenever any error is encountered and rest of the promise should not get executed. I would appreciate if anyone could help me with this.
Upvotes: 3
Views: 741
Reputation: 842
This code has not been tested and should as such be though of more as pseudocode than an actual solution:
Try to either restructure your code more like this:
const request = require('request-promise-native')
postRequest(req, headersObj, loginUrl, Constants.loginData)
.then(loginSuccess)
.then(handleSavedQuerySearchResponse)
.then(handleSearchSoaResponse)
.then(handleCreateObjectSoaResposne)
.then(handleUpdateObjectSoaResponse)
.catch(console.error)
function postRequest(request: any, header: any, reqUrl: string, jsonData: any): Promise<any> {
return request.post({
headers: header,
url: reqUrl,
body: JSON.stringify(jsonData),
}, (err: any, resp: any, bodyParam: any) => {
resolve({error: err, response: resp, body: bodyParam});
});
}
Where the error handling is a part of the promise chain.
Or you can do pretty much the same with async/await.
You could add your onFailure function here instead of just console.error if you want to do some actual error handling
Upvotes: 2