gpt4 book ai didi

javascript - Node JS : Not calling promise reject() callback stops the execution of the program

转载 作者:太空宇宙 更新时间:2023-11-03 22:56:49 26 4
gpt4 key购买 nike

看来我误解了 Promise 机制。在下面的代码中:

async function CreateSession()
{
var sessionId = await new Promise((resolve, reject) => {
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
log.debug("Session created successfully")
resolve(body["session-id"]);
}
else
{
log.error("Failed to create session:");
log.error(error);
// reject(error);
}
});
});

log.debug(`Session Id: ${sessionId}`);
return sessionId;
}

对reject()进行注释是为了理解该机制。当按如下方式调用上述 CreateSession() 函数并确保发生错误时:

async function MyFunction()
{
var sessionId = await CreateSession();
AnotherCode();
}

整个程序停止,永远不会到达 CreateSession 中等待之后的代码,永远不会调用 AnotherCode(),即使我为未捕获的异常放置一个处理程序,它也不会捕获任何错误。

我的问题:

  • 为什么当没有调用reject()时程序会停止?
  • 如果这是一个错误,为什么未捕获的异常处理程序不会调用它?
  • 当 Promise 无法运行其代码时,如何忽略错误?

最佳答案

Why does the program stops when reject() is not called?

因为等待。程序等待 promise 解决拒绝。它无法以某种方式检测到 Promise 构造函数内的代码已完成执行(即使可以 - “标准”行为应该是什么?)并且没有更多代码。

来自MDN :

An async function can contain an await expression that pauses the execution of the async function to wait for the passed Promise's resolution, then resumes the async function's execution and evaluates as the resolved value.

对于一些“幕后”见解,您可能需要查看 Babel 等转译器生成的 ES5 代码(IIRC 它使用生成器来处理此问题)。

If it's an error why it is not called by the handler for uncaught exceptions?

如果既没有使用reject抛出也没有传递error,那么程序就不知道error是一个错误。

How do I ignore the an error when a promise fails to run its code?

resolve(而不是reject)或reject并围绕await执行经典的try/catch代码

关于javascript - Node JS : Not calling promise reject() callback stops the execution of the program,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59812277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com