Returning promise data to the calling function - javascript

let func1 = function() {
return new Promise((resolve,reject) => {
let someVal = 5;
if (condition) {
resolve(someVal);
}
else {
reject('error occured');
}
});
}
let callingFunction = function() {
func1().then((res) => {
console.log("result",res); /* want to return res to the callingFunction */
return res; /* doesn't work as it returns to the .then not to the callingFunction I guess. */
});
}
let finalData = callingFunction();
Is it feasible to send the result from .then block of promise to callingFunction so that I get result in finalData?

let callingFunction = function() {
return func1().then((res) => {
console.log("result",res)
return res
})
}
callingFunction().then((res) => {
let finalData = res
})

The thing is that promise is an asynchronous operation, hence let finalData = callingFunction(); evaluates to undefined. If you'd like to use promise's result in callingFunction(), just pass res as an argument to it like this:
let func1 = function() {
return new Promise((resolve,reject) => {
let someVal = 5;
if (condition) {
resolve(someVal);
}
else {
reject('error occured');
}
});
}
func1().then((res) => {
console.log("result",res); /* want to return res to the callingFunction */
callingFunction(res);
});

Related

check if user in group ActiveDirectory.js node.js

In c# I would write something like this:
bool HasRole(string userName, string[] groupNames)
{
var ad = new ActiveDirectory();
return groupsNames.Any(groupName => ad.IsUserInGroup(userName, groupName);
}
and then just
if (HasRole("UserName", new[] {"group1", "group2"}))
//do something
in javascript it looks like all things are doing asynchronously, I've read about promises and so on, and tried this:
const ActiveDirectory = require('activedirectory2');
const Promise = require('promise');
const globals = require('./globals');
const activeDirectory = new ActiveDirectory(globals.AdConfig);
hasRole(msg, ...groupNames) {
if (groupNames == null || groupNames == undefined || groupNames.length == 0)
return false;
let promises = [];
groupNames.forEach(groupName => {
let promise = new Promise((resolve, reject) => {
activeDirectory.isUserMemberOf(msg.envelope.user.name, groupName, function (err, isMember) {
if (err) {
reject(err)
}
resolve(isMember);
});
});
promises.push(promise);
});
//I don't clearly understand how I can return promise result only or promise with the right result
let hasRole = false;
promises.forEach(promise => promise.done(result => {
if (result)
hasRole = result;
}));
return hasRole;
So how can write something like:
if (hasRole(msg, 'group1', 'group2'))
//do something...
I suppose I should return promise but how I can do it if i need to check multiple groups?
UPDATE
I wrapped the forEach loop in promise:
return new Promise((resolve, reject) => {
promises.forEach(promise => promise.done(result => {
if (result)
return resolve(result);
}));
and then:
hasRole(msg, 'group1', 'group2').done(result => {
if (result)
//do...
});
May there is another way?
Found a solution. Promises.all is what i needed.
Result code:
hasRole(msg, ...groupNames) {
let promises = [];
groupNames = groupNames.filter(x => x.trim().length > 0);
if (groupNames == undefined || groupNames.length == 0)
{
promises.push(new Promise.resolve(false));
return Promise.all(promises);
}
groupNames.forEach(groupName => {
let promise = new Promise((resolve, reject) => {
activeDirectory.isUserMemberOf(msg.envelope.user.name, groupName, function (err, isMember) {
if (err) {
reject(err)
}
resolve(isMember);
});
});
promises.push(promise);
});
return Promise.all(promises);
}

Javascript promises giving TypeError function is undefined

The code below gives a correct result.
But if then(callback('sum')) is removed from the promise sumOfPromises and added to the call to sumOfPromises (like this : sumOfPromises().then(callback('sum'))) then I get TypeError: sumOfPromises(...) is undefined.
There is someting wrong in sumOfPromises that I cannot understand.
<pre>P_1 is : <span id=p_1>p_1</span></pre>
<pre>P_2 is : <span id=p_2>p_2</span></pre>
<pre>Sum is : <span id=sum>sum</span></pre>
<script>
promise_1().then(callback('p_1'));
promise_2().then(callback('p_2'));
sumOfPromises(); // sumOfPromises().then(callback('sum')); gives TypeError: sumOfPromises(...) is undefined (see below)
function callback(tag) {
const result = obj => {
let e = document.getElementById(tag);
e.innerHTML = obj;
};
return result
}
function sumOfPromises() {
const promises = [promise_1(), promise_2()];
Promise.all(promises).then(function (data) {
return sumOfData(data)
}).then(callback('sum')); // then moved to top gives TypeError: sumOfPromises(...) is undefined (see upper)
}
function sumOfData(data) {
const [p_1, p_2] = data;
console.log('sumOfData input p_1 '+p_1);
console.log('sumOfData input p_2 '+p_2);
return new Promise ( (resolve) => {
var result = p_1 + p_2;
console.log('sumOfData result '+result);
resolve(result)
});
}
function promise_1() {
return new Promise((resolve) => {
const value = Math.random();
console.log('promise_1 value '+value);
resolve(value);
})
}
function promise_2() {
return new Promise((resolve, reject) => {
const value = - Math.random();
console.log('promise_2 value '+value);
resolve(value);
})
}
</script>
You are not returning anything in sumOfPromises, so you canĀ“t attach callbacks to it since its undefined:
function sumOfPromises() {
const promises = [promise_1(), promise_2()];
return Promise.all(promises).then(function (data) { // Add 'return' here
return sumOfData(data)
}).then(callback('sum'));
}
You need to return promise from sumOfPromises. Since in your code you don't have a return statement in sumOfPromises javaScript implicitly return undefined so you end up with a call like this
undefined.then(callback('sum')); // which is an error
<pre>P_1 is : <span id=p_1>p_1</span></pre>
<pre>P_2 is : <span id=p_2>p_2</span></pre>
<pre>Sum is : <span id=sum>sum</span></pre>
<script>
promise_1().then(callback('p_1'));
promise_2().then(callback('p_2'));
sumOfPromises().then(callback('sum'));
function callback(tag) {
const result = obj => {
let e = document.getElementById(tag);
e.innerHTML = obj;
};
return result
}
function sumOfPromises() {
const promises = [promise_1(), promise_2()];
return Promise.all(promises).then(function (data) {
return sumOfData(data)
})
}
function sumOfData(data) {
const [p_1, p_2] = data;
console.log('sumOfData input p_1 '+p_1);
console.log('sumOfData input p_2 '+p_2);
return new Promise ( (resolve) => {
var result = p_1 + p_2;
console.log('sumOfData result '+result);
resolve(result)
});
}
function promise_1() {
return new Promise((resolve) => {
const value = Math.random();
console.log('promise_1 value '+value);
resolve(value);
})
}
function promise_2() {
return new Promise((resolve, reject) => {
const value = - Math.random();
console.log('promise_2 value '+value);
resolve(value);
})
}
</script>

Variable Retains Original Value Despite Having New Value Earlier and Further within a Function

let getProjects = function() {
try {
return axios.get('https://app.asana.com/api/1.0/projects/')
} catch (error) {
console.error(error)
}
}
let getTasks = function(project) {
try {
return axios.get('https://app.asana.com/api/1.0/projects/'+project+'/tasks')
} catch (error) {
console.error(error)
}
}
async function getAsanaData() {
let projects = await getProjects()
projects = projects.data.data
projects.map(async (project) => {
//project.attachments = []
let tasks = await getTasks(project.gid)
if(tasks != undefined){
tasks = tasks.data.data
project.tasks = tasks
//console.log(projects)
}
})
console.log(projects)
return projects
}
Promise.try(() => {
return getAsanaData();
}).then((result) => {
//console.log(util.inspect(result, {showHidden: false, depth: null}))
//var asanaData = safeJsonStringify(result);
//fs.writeFile("thing.json", asanaData);
})
.catch(err=>console.log(err))
In getAsanaData(), projects has a new value after project.tasks = tasks.
However, it's original value is printed by console.log(projects) before return projects.
This of course also means that the original value rather than the necessary new value will be returned.
What is the cause and how do I resolve this?
Try this:
async function getAsanaData() {
let projects = await getProjects()
return Promise.all(projects.data.data.map(async (project) => {
let tasks = await getTasks(project.gid)
project.tasks = !!tasks ? tasks.data.data : project.tasks
return project
}))
}
This will go through the async calls to getTasks and return for each the project. Then you should get them all resolved via Promise.all

Synchronized in typescript angular 5

I have the following code.
public async getOrderInforAsync(customerOrderId) {
return new Promise((resolve, reject) => {
this.orderEntryService.getCommissionIncentives(customerOrderId)
.subscribe(
response => {
Object.assign(this.order, response);
this.order.bookingDate = this.order.bookingDate ? new Date(this.order.bookingDate) : null;
this.order.estBillDate = this.order.estBillDate ? new Date(this.order.estBillDate) : null;
this.order.orderSplit.forEach(element => {
element.rcNumberFullName = `${this.order.customerOrderRCNumber}${element.rcNumberSuffix}`;
});
this.initialQuantityAllocated();
this.orderSummary.allocatedEstCommissionPercent = this.calculateTotalOrderPercent();
this.orderSummary.allocatedEstCommissionAmount = this.calculateTotalOrderAmount();
this.highlight = this.checkOrderSummary(this.orderSummary.allocatedEstCommissionPercent, this.orderSummary.allocatedEstCommissionAmount);
this.calculateAllocatedActualPercent();
this.calculateAllocatedActualAmount();
this.onChangeEstSalesPrice();
resolve();
},
error => {
reject();
}
);
});
}
Sometimes the resolve() is called before this.calculateAllocatedActualPercent() and this.calculateAllocatedActualAmount() are done.
So how to make this code run synchronized, it means all functions on this block code had done before resolve() called?
Try this :
public async getOrderInforAsync(customerOrderId) {
return new Promise((resolve, reject) => {
this.orderEntryService.getCommissionIncentives(customerOrderId)
.subscribe(
response => {
Object.assign(this.order, response);
this.order.bookingDate = this.order.bookingDate ? new Date(this.order.bookingDate) : null;
this.order.estBillDate = this.order.estBillDate ? new Date(this.order.estBillDate) : null;
this.order.orderSplit.forEach(element => {
element.rcNumberFullName = `${this.order.customerOrderRCNumber}${element.rcNumberSuffix}`;
});
this.initialQuantityAllocated();
this.orderSummary.allocatedEstCommissionPercent = this.calculateTotalOrderPercent();
this.orderSummary.allocatedEstCommissionAmount = this.calculateTotalOrderAmount();
this.highlight = this.checkOrderSummary(this.orderSummary.allocatedEstCommissionPercent, this.orderSummary.allocatedEstCommissionAmount);
await this.calculateAllocatedActualPercent();
await this.calculateAllocatedActualAmount();
this.onChangeEstSalesPrice();
resolve();
},
error => {
reject();
}
);
});
}
async calculateAllocatedActualPercent(){
return new Promise(resolve,reject){
// call api
if (data)
resolve(data);
else
reject()
}
}
async calculateAllocatedActualAmount(){
return new Promise(resolve,reject){
// call api
if (data)
resolve(data);
else
reject()
}
}
An async function returns a Promise. And to declare a function as async, you need to have an await call inside it.
Change your observable returned from this.orderEntryService.getCommissionIncentives(customerOrderId) .toPromise() and then await it.
Try this:
public async getOrderInforAsync(customerOrderId) {
try {
const response = await this.orderEntryService
.getCommissionIncentives(customerOrderId).toPromise();
this.order = { ...response };
this.order.bookingDate = this.order.bookingDate ? new Date(this.order.bookingDate) : null;
this.order.estBillDate = this.order.estBillDate ? new Date(this.order.estBillDate) : null;
for (let i = 0; i < this.order.orderSplit; i++) {
const element = this.order.orderSplit[i];
element.rcNumberFullName = `${this.order.customerOrderRCNumber}${element.rcNumberSuffix}`
}
this.initialQuantityAllocated();
this.orderSummary.allocatedEstCommissionPercent = this.calculateTotalOrderPercent();
this.orderSummary.allocatedEstCommissionAmount = this.calculateTotalOrderAmount();
this.highlight = this.checkOrderSummary(this.orderSummary.allocatedEstCommissionPercent, this.orderSummary.allocatedEstCommissionAmount);
this.calculateAllocatedActualPercent();
this.calculateAllocatedActualAmount();
this.onChangeEstSalesPrice();
return response;
} catch (error) {
return error;
}
}

simple async function in javascript

I'm playing with async/await and with the code below, shouldn't response be empty or null until the setTimeout in the response const has finished after 5 seconds? and shouldn't response return xyz instead of 1?
async function test() {
try {
const response = await setTimeout(
function() {
const obj = {};
obj.text = "xyz";
console.log('should console log after 5 seconds')
return obj;
},
5000)
if (response) {
console.log(`response is ${response}`)
console.log(`response.text is ${response.text}`)
}
}
catch(err) {
console.log(err)
}
}
test();
You have to put a Promise to await the setTimeout().
async function test() {
try {
const response = await new Promise((resolve) => {
setTimeout(
function() {
const obj = {};
obj.text = "xyz";
console.log('should console log after 5 seconds')
return resolve(obj);
},
5000)
});
if (response) {
console.log(`response is ${response}`)
console.log(`response.text is ${response.text}`)
}
}
catch(err) {
console.log(err)
}
}
test();
For your code to work as per the expectations, you need to wrap the set timeout in a promise. Check the snippet. Without wrapping it in promise, setTimeout returns value immediately which is the ID value of the timer.
async function test() {
try {
const response = await new Promise(function(resolve, reject) {
setTimeout(
function() {
const obj = {};
obj.text = "xyz";
console.log('should console log after 5 seconds')
resolve(obj);
},
5000)
})
if (response) {
console.log(`response is ${response}`)
console.log(`response.text is ${response.text}`)
}
} catch (err) {
console.log(err)
}
}
test();

Categories

Resources