javascript - 异步与标准回调混合
问题描述
我刚刚开始Promise
在 Javascript 中学习 s,并且偶然发现了async/await
.
据我了解,如果我指定一个函数,则async
javascript 将始终包装我函数的内容并返回 aPromise
而不是我返回的任何内容。
让我们假设以下场景:
async function httpRequest() {
oReq = new XMLHttpRequest();
oReq.addEventListener("load", function() {
return this.responseText;
});
oReq.open("GET", "http://some.url.here");
oReq.send();
}
httpRequest().then(function(httpResult) {
console.log(httpResult);
});
我是否正确假设上述情况不起作用,因为httpRequest()
没有返回任何东西,回调XMLHttpRequest
只返回一些东西,因此我的结果很可能是undefined
?
如果是,我将如何修复httpRequest()
它以便在某个async/await
场景中工作?
解决方案
您在这里拥有的是一个执行异步操作的异步函数,其中该操作不使用承诺。这意味着您需要设置一个函数来显式地管理和返回一个 Promise。您不需要async
此处的关键字,因为您想显式地创建您创建return
的 a Promise
,而不是 async 关键字为您创建的承诺(您无法直接管理)。
function httpRequest() {
// Return a promise (this is what an async function does for you)
return new Promise(resolve => {
const oReq = new XMLHttpRequest();
oReq.addEventListener("load", function() {
// Resolve the promise when the async operation is complete.
resolve(this.responseText);
});
oReq.open("GET", "http://some.url.here");
oReq.send();
};
}
现在该函数显式返回了一个 Promise,它可以await
像async
函数一样被编辑。或与then()
任何承诺一样使用。
async function someFunction() {
// await
const awaitedResponse = await httpRequest();
console.log(awaitedResponse);
// or promise chain
httpRequest().then(responseText => console.log(responseText));
};
推荐阅读
- c++ - c ++迭代器,替代语法?
- php - WooCommerce 管理员订单页面 - 删除电子邮件和电话上的超链接
- python - python中的代理链
- reactjs - React - 使用状态动态添加输入标签
- ios - 我的 GMSMarker 显示在左上角,我想在中心 Objective-c 上显示它
- python - NoReverseMatch at / Reverse for 'course_detail' 没有找到参数 '('',)'。尝试了 1 种模式:['course/(?P
[-a-zA-Z0-9_]+)/$'] - python - 为什么在它自己的构造函数中调用 super.__init__() 并且这是某种类型的递归?
- apache-kafka - Kafka Mirrormaker 和记录编码
- javascript - 如何在 Promise 函数中抛出不同的错误?
- keras - 使用 Keras 和 TF2.0 的 Eager vs 图形模式