【发布时间】:2021-12-15 11:21:36
【问题描述】:
在下面的代码中,我在 async 函数内有 createPost(),但我不想在其上使用 await,因此它会阻止函数其余部分的执行。这就是我使用then的原因。
外部async函数有很多其他函数使用await,所以不能更改。
问题
因为createPost() 是async/await 函数(见下文)。如何解析/拒绝外部函数中的then/catch?
module.exports = async (p) => {
// lots of code here
const t = await function1();
// lots of code here
createPost(p).then(message => {
// lots of code here
console.log("ok " + message);
}).catch(message => {
console.log("failed " + message);
});
};
createPost()
module.exports = async (p) => {
// lots of code here
try {
const r = await getStat();
} catch (error) {
console.log(error);
};
};
【问题讨论】:
-
为什么第一个模块是
async? -
很遗憾我不明白你的问题,你能描述更多...你想做什么?
-
createPost()中的 try-catch 块将捕获您的异常,因此您可以删除createPost()级别的 try-catch,这样任何错误都会导致返回被拒绝的承诺,并且然后在.catch()内处理 -
@SandraSchlichting "我需要对
createPost()进行哪些更改,以便可以在外部函数中使用then/catch?" - 呃,没有?async function总是返回一个承诺,你可以简单地调用.then()。 “我如何指定外部函数获取的message?” - 好吧,你的createPost实现没有return任何东西,所以承诺总是解析为undefined。跨度> -
@Bergi 谢谢。如果我可以将您的评论标记为答案,我会这样做 =)
标签: javascript node.js ecmascript-6 async-await