This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've been trying to get user locales using expo, on react-native. Problem is, i need to get the promise value and pass it to return function. The value is currently 'undefined'.
This is the code:
export default locales = () => {
var locals;
Expo.DangerZone.Localization.getCurrentLocaleAsync().then((value) => {
locals = value;
});
return locals;
}
How do i get the promise value and return it on function?
return locals; happens before your promise returns and so will be undefined. You need to use a callback:
export default locales = (callback) => {
Expo.DangerZone.Localization.getCurrentLocaleAsync().then((value) => {
return callback(value);
});
}
then you can access the value like this:
your_module.locales((locals)=>{
// use locals here
});
or, if you have access to async/await in newer versions of node:
export default locales = async () => {
let value = await Expo.DangerZone.Localization.getCurrentLocaleAsync()
return value;
}
and then you would call the function like this:
let locals = await your_module.locales()
but, considering there is a function Expo.DangerZone.Localization.getCurrentLocaleAsync() are you sure a synchronous version, getCurrentLocaleSync() or getCurrentLocale() don't exist? That would make this much easier you could just call the function directly and obtain the value.
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 24 days ago.
I have this script. In the createApp function, I have a variant variable.
And you can see that I do a console.log(variant) below axios.get(). It logs 'ealjapd (it is the variant content).
But it is supposed to change to results.data.variants[0]. But it isn't changing... any suggestions?
<script>
if (document.querySelector('#add-to-cart-form')) {
const app = Vue.createApp({
delimiters: ['${', '}'],
setup() {
let variant = Vue.ref('ea´ljapd');
axios.get('/products/{{product.handle}}.js').then((results) => {
variant = Vue.ref(results.data.variants[0]);
console.log(variant);
});
const addToCart = (event) => {
event.preventDefault();
axios
.post('/cart/add.js', data)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
};
return {
variant,
};
},
}).mount('#add-to-cart-form');
}
</script>
I can't figure it out, I need help
try this
variant.value = results.data.variants[0]
reference here
https://vuejs.org/guide/essentials/reactivity-fundamentals.html#reactive-variables-with-ref
This question already has answers here:
How can I pass variable into an evaluate function?
(7 answers)
Closed 1 year ago.
I tried different ways like add it to unnamed function, but without success. Thank you.
var selector = '.tile-hover-target';
const prods = await page.$$eval(resultsSelector, function (msgs) {
return msgs.map(function (selector, msg) {
return {
link: msg.querySelector(selector).href.trim(),
}
}.bind(null, selector))
});
According to the Puppeteer documentation, arguments need to be passed after the function. This works fine:
var sel = '.product-card__main';
const prods = await page.$$eval(resultsSelector, function (msgs, sel) {
return msgs.map(function (selector, msg) {
return {
link: msg.querySelector(selector).href.trim(),
}
}.bind(null, sel))
}, sel);
The two of the following result in different things although they look like the same thing.
1
const addBlogPost = dispatch => {
return () => {
dispatch({type: 'add_blogpost'});
}
};
2
const addBlogPost = dispatch => dispatch({type: 'add_blogpost'});
Could anyone point out how are they different?
You can use this site to compile es6 arrow functions to vanilla JS to easily see the difference.
The first one compiles to this
var addBlogPost = function addBlogPost(dispatch) {
return function () {
dispatch({
type: 'add_blogpost'
});
};
};
While the second compiles to this
var addBlogPost = function addBlogPost(dispatch) {
return dispatch({
type: 'add_blogpost'
});
};
The first returns a function that has a dispatch while the second one returns a dispatch directly.
The result will always be the same as both functions are retuning the same thing.
The only difference is:
In the first function, you're returning a function which returns an object that returns dispatch function.
In the second function, you're returning your dispatch function directly.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I have following code:
const get = (ip,key) => {
mysql.query(`SELECT content FROM sessions WHERE ip = "${ip}" AND name = "${key}" ORDER BY id DESC LIMIT 1`,(err,result) => {
if(err) throw err
console.log('Callback:',result[0].content)
return result[0].content
})
}
console.log('Return:',get('10.0.0.9','test'))
It produces following output:
Return: undefined
Callback: test content
Why doesn't my function return anything?
The value "test content" is what's actually returned by the handler (or callback) you pass to mysql.query().
Your function get actually do not return anything.
You are dealing with an asynchronous function.
There is several way to solve your problem.
Simplest one, would be to pass a third argument to your get function, a callback function an call it in your mysql handler. Something like:
const get = (ip,key,callback) => {
mysql.query(`SELECT content FROM sessions WHERE ip = "${ip}" AND name = "${key}" ORDER BY id DESC LIMIT 1`,(err,result) => {
if(err) throw err
console.log('Callback:',result[0].content);
// Call you custom callback here to forward result
callback( result[0].content );
})
}
get('10.0.0.9','test', (result) => console.log('Return:', result));
An other approach, more modern would be to use Promise
And the most 'up to date' solution would be to use a async/await
Sometimes my Redux selectors are quite complicated. I need some means for debugging each step in the chain.
Here is a simplified selector as an example:
export const selectCompletedFilesForSaveToServer = state => {
return state
.getIn(['file', 'saveToServerQueue'])
.filterNot(item => item.get('isPosting'))
.valueSeq();
};
And this is what I want to do:
export const selectCompletedFilesForSaveToServer = state => {
return state
.getIn(['file', 'saveToServerQueue'])
.intercept(item => console.log(item.toJS())
.filterNot(item => item.get('isPosting'))
.intercept(item => console.log(item.toJS())
.valueSeq();
};
I.e. the intercept function should take whatever collection is thrown at it (Map, List, etc), iterate over the collection and then return the original collection for further chaining.
I tried to use .forEach(), but I didn't understand how it works.
My current solution is to manually break up the chain into separate intermediate variables for inspection, but this is not a nice solution.
Well.. while writing my question I kind of got some perspective and solved it.
The .filter() function essentially is a peek function. Just remember to return true..
export const selectCompletedFilesForSaveToServer = state => {
return state
.getIn(['file', 'saveToServerQueue'])
.filter(item => {
console.log(item.toJS());
return true;
});
.filterNot(item => item.get('isPosting'))
.filter(item => {
console.log(item.toJS());
return true;
});
.valueSeq();
};
edit:
I found an even better function: .update(). It's chainable and takes a custom function as an argument. The custom function gets the collection as argument and should return the collection as well (in my use case).
https://facebook.github.io/immutable-js/docs/#/Collection/update
New example:
export const selectCompletedFilesForSaveToServer = state => {
const peek = function(collection) {
console.log(collection.toJS());
return collection;
};
return state
.getIn(['file', 'saveToServerQueue'])
.update(peek);
.filterNot(item => item.get('isPosting'))
.update(peek);
.valueSeq();
};