- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
看来我误解了 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(),即使我为未捕获的异常放置一个处理程序,它也不会捕获任何错误。
我的问题:
最佳答案
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/
我是一名优秀的程序员,十分优秀!