Maybe i have a stoopid question, but i want to return function call with promise .then and with async function, to later use this on express.js
function search (opts) {
//const url
//const callback
return request(url, callback)
.then(res => {
const promisesAccounts = res.accounts.map( el => request(el, callbackPage));
const promisesKeyword = res.keyword.map( el => request(el, callbackPage));
const hello = async () => {
const obj = {};
const promiseA = await Promise.all(promisesAccounts);
const promiseB = await Promise.all(promisesKeyword);
obj.accounts = promiseA;
obj.keywords = promiseB;
console.log(obj);
}
hello()
})
}
Maybe somehow i can return obj to later use it on express app like this :
app.get('/', (req, res) => {
search()
.then (result => res.json(result)) //hello async obj result
})
asked Oct 12, 2018 at 7:59
Albert Jovinskyi
3491 gold badge3 silver badges14 bronze badges
2 Answers 2
You can just return your function like this
function search (opts) {
//const url
//const callback
return request(url, callback)
.then(res => {
const promisesAccounts = res.accounts.map( el => request(el, callbackPage));
const promisesKeyword = res.keyword.map( el => request(el, callbackPage));
const hello = async () => {
const obj = {};
const promiseA = await Promise.all(promisesAccounts);
const promiseB = await Promise.all(promisesKeyword);
obj.accounts = promiseA;
obj.keywords = promiseB;
console.log(obj);
}
return hello;
})
}
To use this you can then
request
.then(async myFunc => {
const value = await muFunc(parameter_here)
})
answered Oct 12, 2018 at 8:08
Prasanna
4,7461 gold badge26 silver badges47 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Albert Jovinskyi
myFunc thats reference to hello func ?
Prasanna
@AlbertJovinskyi Yes! It refers to the hello func. But if you want just the computed value of the function Sergii's answer is what you should look up to
Albert Jovinskyi
yes thank you i'll gonna try with your variant, its more intresting)
Please try:
function search (opts) {
return request(url, callback)
.then(res => {
const promisesAccounts = res.accounts.map( el => request(el, callbackPage));
const promisesKeyword = res.keyword.map( el => request(el, callbackPage));
const hello = async () => {
const obj = {};
const promiseA = await Promise.all(promisesAccounts);
const promiseB = await Promise.all(promisesKeyword);
obj.accounts = promiseA;
obj.keywords = promiseB;
console.log(obj);
return obj;
}
return hello()
})
}
answered Oct 12, 2018 at 8:08
Sergii Vorobei
1,50713 silver badges19 bronze badges
Comments
lang-js