也许我有一个愚蠢的问题,但是我想返回带有promise .then和async函数的函数调用,以便以后在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()
})
}
也许我可以通过某种方式返回obj以便以后在Express应用程序上使用它:
app.get('/', (req, res) => {
search()
.then (result => res.json(result)) //hello async obj result
})
答案 0 :(得分:1)
请尝试:
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()
})
}
答案 1 :(得分:1)
您可以return
像这样
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;
})
}
要使用此功能,您可以
request
.then(async myFunc => {
const value = await muFunc(parameter_here)
})