对于这里的许多人来说,这可能是一件简单的事情,但是正如documentation解释the expression can be a promise or any value to wait for
这里我有一个返回诺言的函数,当我用then
来解决诺言时
streamIdea(ideaobj).then(i => {
idea = i;
});
但是当我尝试以等待方式解决诺言
idea = await streamIdea(ideaobj);
它引发错误
idea = await streamIdea(ideaobj);
^^^^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:599:28)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
有人可以解释为什么以及我如何在等待时解决诺言吗? 谢谢
编辑:由于他们在没有完全理解的情况下将重复标记为重复,所以我已经检查了我被推荐的问题,但是它不起作用,将不胜感激
这是流的想法功能
streamIdea: async (idea) => {
return new Promise((resolve, reject) => {
const promises = [];
const indexes = {
solution: -1,
benefits: -1,
situaton: -1
}
if (idea.SOLUTION) {
const index = promises.push(toString(idea.SOLUTION)) - 1;
indexes.solution = index
}
if (idea.BENEFITS) {
const index = promises.push(toString(idea.BENEFITS)) - 1;
indexes.benefits = index
}
if (idea.CURRENT_SITUATION) {
const index = promises.push(toString(idea.CURRENT_SITUATION)) - 1;
indexes.situaton = index
}
if (promises.length > 0) {
Promise.all(promises).then(result => {
if (indexes.solution >= 0) {
idea.SOLUTION = result[indexes.solution];
}
if (indexes.benefits >= 0) {
idea.BENEFITS = result[indexes.benefits];
}
if (indexes.situaton >= 0) {
idea.CURRENT_SITUATION = result[indexes.situaton];
}
resolve(idea);
}, err => {
console.log(err);
reject(err);
});
} else {
resolve(idea);
}
});
}
这是我要解决的功能
get: async (req) => {
let idea = {};
return new Promise((resolve, reject) => {
Ideas.findOne({
where: {
IDEA_ID: req.params.idea_id
},
raw: true
}).then(ideaobj => {
idea = await streamIdea(ideaobj);
console.log('idea',idea);
return db.query(`SELECT
"IDEA_CATEGORIES"."IDEA_CATEGORY_ID",
"LOOKUP"."LOOKUP_ID" "LOOKUP_ID",
"LOOKUP"."NAME" "NAME"
FROM "IDEA_CATEGORIES" "IDEA_CATEGORIES"
LEFT OUTER JOIN "LOOKUPS" "LOOKUP"
ON "IDEA_CATEGORIES"."CATEGORY_ID" = "LOOKUP"."LOOKUP_ID"
WHERE "IDEA_CATEGORIES"."IDEA_ID" = '${req.params.idea_id}';`, { type: db.QueryTypes.SELECT });
}).then(categories => {
//idea.categories = categories;
resolve(toLower(idea));
}).catch(e => {
reject(e);
});
})
}
我的函数在返回承诺并解决异步函数方面是异步的,有人可以在这里解释出什么问题