In javascript, within a VueJS SPA, I'm trying to create a method that will allow me to reduce redundant code by passing the Google Maps Places Service only a place_id and the fields I would like returned.
getPlaceDetails (place, fields) {
this.$refs.mapRef.$mapPromise.then((map) => {
var placesServices = new window.google.maps.places.PlacesService(map)
placesServices.getDetails({ placeId: String(place.place_id), fields: fields }, (result, status) => {
if (status === window.google.maps.places.PlacesServiceStatus.OK) {
alert(JSON.stringify(result))
return result
}
})
})
}
I'm calling the above method from within another method:
var place = this.getPlaceDetails(place, ['name', 'geometry', 'place_id'])
It is invoked successfully... and the alert shows the desired JSON.. but place is null. I've tried using
var vm = this
above
var placesServices
and assigning the result to an app level variable... even inside of a .then after the first promise... like so:
getPlaceDetails (place, fields) {
this.$refs.mapRef.$mapPromise.then((map) => {
var vm = this
var placesServices = new window.google.maps.places.PlacesService(map)
placesServices.getDetails({ placeId: String(place.place_id), fields: fields }, (result, status) => {
if (status === window.google.maps.places.PlacesServiceStatus.OK) {
alert(JSON.stringify(result))
vm.tempPlace = result
}
})
}).then(function () {
return this.tempPlace
})
}
How can I get the method to return the result object??
Promises
A promise is an object that will resolve (or reject) in some point in the future. This is necessary to execute asynchronous tasks (e.g. http-calls) that take an undefined amount of time to finish.
Promises can be chained i.e. get executed one after another. This is what the .then method does. With .then you pass a function that will be executed as soon as the promise is finished. This function will receive the object that was returned by the previous promise.
Your method
getPlaceDetails (place, fields) {
return this.$refs.mapRef.$mapPromise.then((map) => {
var vm = this;
var placesServices = new window.google.maps.places.PlacesService(map);
placesServices.getDetails({ placeId: String(place.place_id), fields: fields }, (result, status) => {
if (status === window.google.maps.places.PlacesServiceStatus.OK) {
alert(JSON.stringify(result));
return result;
}
});
});
}
This Method will return a promise that - at some point in the future - will yield the desired result.
When you want to call the method you get that promise and have to handle it, again by passing a function (using .then) that will be executed once the result is ready.
this.getPlaceDetails(...).then((result) => {
// handle your result
}}
Alternatively you could use the await operator to wait until the promise is finished:
var place = await this.getPlaceDetails(...);
Instead of returning the data, you may consider assigning the JSON to a Vue watched data variable, like so:
var somePlace = new Vue({
el: '#someEl',
data: {
message: 'Hello robwolf.io',
tempPlace: {} // <- variable waiting for your asynchronous data if it comes thru
},
methods: {
getPlaceDetails (place, fields) {
// [...your promise code here...]
}).then((result) => {
this.tempPlace = JSON.stringify(result)
// return this.tempPlace
})
// [...the .then function must also be an arrow function to have scope access to tempPlace...]
Related
I am reading a JSON object and looping through each item. I am first checking to see if the item already exists in the database and if so I want to log a message. If it doesn't already exist I want to add it.
This is working correctly however, I would like to add a callback or finish the process with process.exit();
Because the mongoose calls are asynchronous I can't put it at the end of the for loop because they haven't finished.
Whats the best way I should handle this?
function storeBeer(data) {
data.forEach((beer) => {
let beerModel = new Beer({
beer_id: beer.id,
name: beer.name,
image_url: beer.image_url
});
Beer.findOne({
'name': beer.name
}).then(function (result) {
if (result) {
console.log(`Duplicate ${result.name}`)
} else {
beerModel.save(function (err, result) {
console.log(`Saved: ${result.name}`)
});
}
});
});
}
Is there anything I should read up on to help solve this?
One means of managing asynchronous resources is through Promise objects, which are first-class objects in Javascript. This means that they can be organized in Arrays and operated on like any other object. So, assuming you want to store these beers in parallel like the question implies, you can do something like the following:
function storeBeer(data) {
// This creates an array of Promise objects, which can be
// executed in parallel.
const promises = data.map((beer) => {
let beerModel = new Beer({
beer_id: beer.id,
name: beer.name,
image_url: beer.image_url
});
return Beer.findOne({
'name': beer.name
}).then(function (result) {
if (result) {
console.log(`Duplicate ${result.name}`)
} else {
beerModel.save(function (err, result) {
console.log(`Saved: ${result.name}`)
});
}
});
);
});
return Promise.all(promises);
}
Don't forget that the storeBeer function is now asynchronous, and will need to be utilized either through a Promise chain or through async/await.
For example, to add process exit afterwards:
async function main() {
const beers = [ ... ];
await storeBeer(beer);
process.exit(0);
}
You can also modify the above example to invoke the storeBeer function within a try / catch block to exit with a different error code based on any thrown errors.
Good morning !
Currently I am trying to create some kind of simple validation using javascript, but I have a problem with using async functionalities.
Below you can see UI method which iterates through validityChecks collections
checkValidity: function(input){
for(let i = 0; i<this.validityChecks.length; i++){
var isInvalid = this.validityChecks[i].isInvalid(input);//promise is returned
if(isInvalid){
this.addInvalidity(this.validityChecks[i].invalidityMessage);
}
var requirementElement = this.validityChecks[i].element;
if(requirementElement){
if(isInvalid){
requirementElement.classList.add('invalid');
requirementElement.classList.remove('valid');
}else{
requirementElement.classList.remove('invalid');
requirementElement.classList.add('valid');
}
}
}
}
Below is specific collection object which is not working as it was intended
var usernameValidityChecks = [
{
isInvalid: function(input){
var unwantedSigns = input.value.match(/[^a-zA-Z0-9]/g);
return unwantedSigns ? true:false;
},
invalidityMessage:'Only letters and numbers are allowed',
element: document.querySelector('.username-registration li:nth-child(2)')
},
{
isInvalid: async function (input){
return await checkUsername(input.value);
},
invalidityMessage: 'This value needs to be unique',
element: document.querySelector('.username-registration li:nth-child(3)')
}
]
function checkUsername (username) {
return new Promise ((resolve, reject) =>{
$.ajax({
url: "check.php",
type: "POST",
data: { user_name: username },
success: (data, statusText, jqXHR) => {
resolve(data);
},
error: (jqXHR, textStatus, errorThrown) => {
reject(errorThrown);
}
});
});
}
The problem is that to var isInvalid in checkValidity method is returned promise. Can anyone advice how to returned there value instead of promise ? Or how to handle promise there ?
Thank you in advance!
EDIT :
Forgive me, but it is my first time with Stack and probably my question is a little bit inaccurate. Some of objects in collections are also synchronous, I changed usernameValidityChecks. How to handle this kind of situation ? Where I have async and sync method at the same time ?
Instead of below line
var isInvalid = this.validityChecks[i].isInvalid(input);
you can use below code to make code much cleaner and store the desired value on the variable however above suggested solutions are also correct
var isInvalid = await this.validityChecks[i].isInvalid(input).catch((err) => { console.log(err) });
After this line you will get the desired value on isInvalid variable
And also add async keyword in all other isInvalid function definition
Use .then to access the result of a promise:
var isInvalid = this.validityChecks[i].isInvalid(input).then(res => res);
I have a database that's calling for a list of recent messages. Each message is an object and is stored as an Array of these message objects in chatListNew.
Each message object has a property "from", which is the ID of the user who posted it. What I want to do, is loop through this Array and append the actual profile information of the "From" user into the object itself. That way when the Frontend receives the information, it has access to one specific message's sender's profile in that respective message's fromProfile property.
I thought about looping through each one and doing a Promise.All for every one, however, that's hugely expensive if only a handful over users posted hundreds of messages. It would make more sense to only run the mongoose query once for each user. So I invented a caching system.
However, I'm confused as to how to store the promise of a future value inside of an array element. I thought setting the "fromProfile" to the previously called promise would magically hold this promise until the value was resolved. So I used Promise.all to make sure all the promises were completed and then returned by results, but the promises I had stored in the arrays were not the values I had hoped for.
Here is my code:
//chatListNew = an array of objects, each object is a message that has a "from" property indicating the person-who-sent-the-message's user ID
let cacheProfilesPromises = []; // this will my basic array of the promises called in the upcoming foreach loop, made for Promise.all
let cacheProfilesKey = {}; // this will be a Key => Value pair, where the key is the message's "From" Id, and the value is the promise retrieving that profile
let cacheProfileIDs = []; // this another Key => Value pair, which basically stores to see if a certain "From" Id has already been called, so that we can not call another expensive mongoose query
chatListNew.forEach((message, index) => {
if(!cacheProfileIDs[message.from]) { // test to see if this user has already been iterated, if not
let thisSearch = User.findOne({_id : message.from}).select('name nickname phone avatar').exec().then(results => {return results}).catch(err => { console.log(err); return '???' ; }); // Profile retrieving promise
cacheProfilesKey[message.from] = thisSearch;
cacheProfilesPromises.push(thisSearch); // creating the Array of promises
cacheProfileIDs[message.from] = true;
}
chatListNew[index]["fromProfile"] = cacheProfilesKey[message.from]; // Attaching this promise (hoping it will become a value once promise is resolved) to the new property "fromProfile"
});
Promise.all(cacheProfilesPromises).then(_=>{ // Are all promises done?
console.log('Chat List New: ', chatListNew);
res.send(chatListNew);
});
And this is my console output:
Chat List New: [ { _id: '5b76337ceccfa2bdb7ff35b5',
updatedAt: '2018-08-18T19:50:53.105Z',
createdAt: '2018-08-18T19:50:53.105Z',
from: '5b74c1691d21ce5d9a7ba755',
conversation: '5b761cf1eccfa2bdb7ff2b8a',
type: 'msg',
content: 'Hey everyone!',
fromProfile:
Promise { emitter: [EventEmitter], emitted: [Object], ended: true } },
{ _id: '5b78712deccfa2bdb7009d1d',
updatedAt: '2018-08-18T19:41:29.763Z',
createdAt: '2018-08-18T19:41:29.763Z',
from: '5b74c1691d21ce5d9a7ba755',
conversation: '5b761cf1eccfa2bdb7ff2b8a',
type: 'msg',
content: 'Yo!',
fromProfile:
Promise { emitter: [EventEmitter], emitted: [Object], ended: true } } ]
Whereas I was hoping for something like:
Chat List New: [ { _id: '5b76337ceccfa2bdb7ff35b5',
updatedAt: '2018-08-18T19:50:53.105Z',
createdAt: '2018-08-18T19:50:53.105Z',
from: '5b74c1691d21ce5d9a7ba755',
conversation: '5b761cf1eccfa2bdb7ff2b8a',
type: 'msg',
content: 'Hey everyone!',
fromProfile:
Promise {name: xxx, nickname: abc... etc} },
{ _id: '5b78712deccfa2bdb7009d1d',
updatedAt: '2018-08-18T19:41:29.763Z',
createdAt: '2018-08-18T19:41:29.763Z',
from: '5b74c1691d21ce5d9a7ba755',
conversation: '5b761cf1eccfa2bdb7ff2b8a',
type: 'msg',
content: 'Yo!',
fromProfile:
{name: xxx, nickname: abc... etc} } ]
Thank you guys! Open to other ways of accomplishing this :)
Pete
When a Promise is assigned to a variable, that variable will always be a Promise, unless the variable is reassigned. You need to get the results of your Promises from your Promise.all call.
There's also no point to a .then that simply returns its argument, as with your .then(results => {return results}) - you can leave that off entirely, it doesn't do anything.
Construct the array of Promises, and also construct an array of from properties, such that each Promise's from corresponds to the item in the other array at the same index. That way, once the Promise.all completes, you can transform the array of resolved values into an object indexed by from, after which you can iterate over the chatListNew and assign the resolved value to the fromProfile property of each message:
const cacheProfilesPromises = [];
const messagesFrom = [];
chatListNew.forEach((message, index) => {
const { from } = message;
if(messagesFrom.includes(from)) return;
messagesFrom.push(from);
const thisSearch = User.findOne({_id : from})
.select('name nickname phone avatar')
.exec()
.catch(err => { console.log(err); return '???' ; });
cacheProfilesPromises.push(thisSearch);
});
Promise.all(cacheProfilesPromises)
.then((newInfoArr) => {
// Transform the array of Promises into an object indexed by `from`:
const newInfoByFrom = newInfoArr.reduce((a, newInfo, i) => {
a[messagesFrom[i]] = newInfo;
return a;
}, {});
// Iterate over `chatListNew` and assign the *resolved* values:
chatListNew.forEach((message) => {
message.fromProfile = newInfoByFrom[message.from];
});
});
A Promise is an object container, like a Array. The difference being that a Promise holds a value that will sometimes be.
So, since you do not know when the value will be resolved in Promise jargon, generally you tell the promise what to do with the value, when it is resolved.
So for example,
function (id) {
const cache = {}
const promise = expensiveQuery(id)
// promise will always be a promise no matter what
promise.then(value => cache[id] = value)
// After the callback inside then is executed,
// cache has the value you are looking for,
// But the following line will not give you the value
return cache[params.id]
}
Now, what you might do to fix that code is, return the promise when the query is run for the first time, or return the cached value.
// I moved this out of the function scope to make it a closure
// so the cache is the same across function calls
const cache = {}
function (id) {
if(cache[id]) return cache[id]
const promise = expensiveQuery(id)
// promise will always be a promise no matter what
promise.then(value => cache[id] = value)
// now we just return the promise, because the query
// has already run
return promise
}
Now you'll have a value or a promise depending on whether the function has already been called once before for that id, and the previous call has been resolved.
But that's a problem, because you want to have a consistent API, so lets tweak it a little.
// I moved this out of the function scope to make it a closure
// so the cache is the same across function calls
const cache = {}
function cachingQuery (id) {
if(cache[id]) return cache[id]
const promise = expensiveQuery(id)
// Now cache will hold promises and guarantees that
// the expensive query is called once per id
cache[id] = promise
return promise
}
Ok, now you always have a promise, and you only call the query once. Remember that doing promise.then doesn't perform another query, it simply uses the last result.
And now that we have a caching query function, we can solve the other problem. That is adding the result to the message list.
And also, we dont' want to have a cache that survives for too long, so the cache can't be right on the top scope. Let's wrap all this inside a cacheMaker function, it will take an expensive operation to run, and it will return a function that will cache the results of that function, based on its only argument.
function makeCacher(query) {
const cache = {}
return function (id) {
if(cache[id]) return cache[id]
const promise = query(id)
cache[id] = promise
return promise
}
}
Now we can try to solve the other problem, which is, assign the user to each message.
const queryUser = makeCacher((id) => User.findOne({_id : id})
.select('name nickname phone avatar')
.exec())
const fromUsers = chatListNew.map((message) => queryUser(message.from))
Promise.all(fromUsers)
.then(users =>
chatListNew.map(message =>
Object.assign(
{},
message,
{ fromProfile: users.find(x => x._id === message.from)})))
.then(messagesWitUser => res.json(messagesWitUser) )
.catch(next) // send to error handler in express
I created a NodeJS program (with Bluebird as Promise library) that handles some validations similar to how the snippet below works, but if I run that script it throws the following error:
Unhandled rejection RangeError: Maximum call stack size exceeded
Apparently, it's doing some recursive function call at the reassigning of the validations functions where I used .bind(ctx)
The way I solved that problem was assigning the Promise factory to obj._validate instead of reassigning obj.validate and use _validate(ctx) where it's needed.
But I still don't realize why that error happened. Can someone explain to me?
// Example validation function
function validate(pass, fail) {
const ctx = this
Promise.resolve(ctx.value) // Simulate some async validation
.then((value) => {
if (value === 'pass') pass()
if (value == 'fail') fail('Validation failed!')
})
}
let validations = [
{name: 'foo', validate: validate},
{name: 'bar', validate: validate},
{name: 'baz', validate: validate},
{name: 'qux', validate: validate}
]
// Reassigning validate functions to a promise factory
// to handle async validation
validations.forEach(obj => {
obj.validate = (ctx) => { // ctx used as context to validation
return new Promise(obj.validate.bind(ctx))
}
})
function executeValidations(receivedValues, validations) {
receivedValues.forEach((obj, i) => {
validations[i].validate(obj) // obj becomes the context to validate
.then(() => console.log('Validation on', obj.name, 'passed'))
.catch(e => console.error('Validation error on', obj.name, ':', e))
})
}
let receivedValues1 = [
{name: 'foo', value: 'pass'},
{name: 'bar', value: 'fail'},
{name: 'baz', value: 'fail'},
{name: 'qux', value: 'pass'},
]
executeValidations(receivedValues1, validations)
let receivedValues2 = [
{name: 'foo', value: 'pass'},
{name: 'bar', value: 'pass'},
{name: 'baz', value: 'fail'},
{name: 'qux', value: 'fail'},
]
executeValidations(receivedValues2, validations)
<script src="//cdn.jsdelivr.net/bluebird/3.4.7/bluebird.js"></script>
EDIT: I think this is a short version of the problem
function fn(res, rej) { return this.foo }
fn = function(ctx) { return new Promise(fn.bind(ctx))}
const ctx = {foo: 'bar'}
fn(ctx)
.then(console.log)
<script src="//cdn.jsdelivr.net/bluebird/3.4.7/bluebird.js"></script>
obj.validate.bind(ctx)
evaluates to an exotic function object with its this value set to ctx. It is still, very much, a function object.
It then appears that
obj.validate = (ctx) => { // ctx used as context to validation
return new Promise(obj.validate.bind(ctx))
sets obj.validate to a function which returns a promise which during its construction synchronously calls its resolver function obj.validate.bind(ctx) (a.k.a. "executor function" in ES6) which returns a promise object whose construction synchronously calls obj.validate.bind(ctx), and so on ad infinitum or the JavaScript engine throws an error.
Hence calling obj.validate a first time initiates an infinite loop of promise prodution by the resolver function.
A further issue with bind usage:
Arrow functions bind their lexical this value when declared. Syntactically Function.prototype.bind can be applied to an arrow function but does not change the this value seen by the arrow function!
Hence obj.validate.bind(ctx) never updates the this value seen within obj.validate if the method was defined using an arrow function.
Edit:
The biggest problem may be overwriting the value of the function which performs the operation:
As posted:
validations.forEach(obj => {
obj.validate = (ctx) => { // ctx used as context to validation
return new Promise(obj.validate.bind(ctx))
}
overwrites the validate property of each validations entry. This property used to be the named function validate declared at the start, but is no longer.
In the short version,
function fn(res, rej) { return this.foo }
fn = function(ctx) { return new Promise(fn.bind(ctx))}
const ctx = {foo: 'bar'}
fn(ctx)
fn = function... overwrites the named function declaration of fn. This means that when fn is called later, the fn of fn.bind(ctx) refers to the updated version of fn, not the original.
Note also that the resolver function must call its first function parameter (resolve) to synchronously resolve a new promise. Return values of the resolver function are ignored.
executeValidations() expects validate() to return a promise, so its better to return a promise. Rejecting a promise is useful when something goes wrong during a validation, but failing a validation test is a normal part of the validation process, not an error.
// Example validation function
function validate(ctx) {
return new Promise((resolve, reject) => {
// Perform validation asynchronously to fake some async operation
process.nextTick(() => {
// Passing validations resolve with undefined result
if (ctx.value === 'pass') resolve()
// Failing validations resolve with an error object
if (ctx.value == 'fail') resolve({
name: ctx.name,
error: 'Validation failed!'
})
// Something went wrong
reject('Error during validation')
})
})
}
Now executeValidations() can map the validations to a list of errors
function executeValidations(receivedValues, validations) {
// Call validate for each received value, wait for the promises to resolve, then filter out any undefined (i.e. success) results
return Promise.all(receivedValues.map( obj => validate(obj)))
.then(results => results.filter(o => o !== undefined))
}
The validations succeeded if there were no errors...
executeValidations(receivedValues1, validations)
.then (errors => {
if (!errors.length)
console.log('Validations passed')
else
errors.forEach(error => console.error(error))
})
executeValidations(receivedValues2, validations)
.then (errors => {
if (!errors.length)
console.log('Validations passed')
else
errors.forEach(error => console.error(error))
})
So I have a situation where I need to build an Object, then inject some items into that Object, and then make an API call and also inject the API's response into that Object. It's a complex Object so we'll just assume that's alright, but anyway, I think that I need to do these 3 things synchronously and using array.forEach means they run asynchronously.
I hope my example is simple enough to understand, but basically I do 3 things:
Create an empty Array of Classes/Classrooms
Loop through an Array of Class IDs and create an Object for each Class
Loop through an Array of Students and push them into a students Array inside the Class Object
Loop through an Array of Options and push them into an options array inside the Class Object
Finally, I have something that could look like this for each Class:
{
class_id: "abc123",
students: [{}, {}, {}],
options: [{}, {}, {}]
}
And finally, here is my code:
// Create Array of Class Objects
var classes = [];
function processArray(array, func) {
return $q(function(resolve, reject) {
array.forEach(function(item, index) {
func(item);
if (index === (array.length - 1)) resolve();
})
})
}
// Create Courier Objects
processArray(classIds, function(id) {
classes.push({class_id: id, students: [], options: []});
}).then(function(response) {
// Inject Students into each Class
processArray(students, function(students) {
_.find(classes, {'class_id': student.class_id}).students.push(student);
}).then(function(response) {
// Inject classOptions into each Class
processArray(classOptions, function(classOption) {
_.find(classes, {'class_id': classOption.class_id}).classOptions.push(classOption);
}).then(function(response) {
// Print the classes
console.log(classes);
})
})
});
I've create a function which does it synchronously but I'd like to know if anyone can think of a much, much cleaner and more efficient way of doing the above. It seems extremely hacky, and maybe I don't even need to do it synchronously if I arranged my functions correctly.
Working with Promise Based APIs that Return Arrays
The processArray function returns a promise that resolves to null.
//WRONG
//Returns a promise that resolves to null
//
function processArray(array, func) {
return $q(function(resolve, reject) {
array.forEach(function(item, index) {
func(item);
if (index === (array.length - 1)) resolve();
})
})
}
To return a promise that resolves to an array, use $q.all.
//RIGHT
//Returns a promise that resolves to an array
//
function processArray(array, func) {
var promiseArray = [];
array.forEach(function(item, index) {
promiseArray.push($q.when(func(item));
});
return $q.all(promiseArray);
}
In either case whether func(item) returns either a value or a promise, $q.when will return a promise.
Be aware that $q.all is not resilient. It will resolve fulfilled with an array of values or it will resolve rejected with the first error.
processArray(array, func)
.then( function onFulfilled(dataList) {
//resolves with an array
$scope.dataList = dataList;
}).catch( function onRejected(firstError) {
console.log(firstError);
});
For more information, see AngularJS $q Service API Reference.
you are using nested promises. These suck. One major advantage of promises is to avoid the 'callback nightmare' of deep nesting.
Use this syntax ...
promise1.then(function(response1) {
// do something with response 1 (and possibly create promise2 here based on response1 if required)
return promise2
}).then(function(response2) {
// do something with response 2
return promise3
}).then(function(response3) {
// do something with response 3
// do something with promise 3???
}).catch(function(errorResponse) {
// will trigger this on a failure in any of the above blocks
// do something with error Response
});