javascript - 对如何在 JS 中使用 Promise 感到困惑
问题描述
我是 JS 新手,正在学习 Promise 以及它们如何在 JS 中使用,我想问一些问题。首先,如果你看下面的代码:
var makeRequest = function (url, method) {
// Create the XHR request
var request = new XMLHttpRequest();
// Return it as a Promise
return new Promise(function (resolve, reject) {
// Setup our listener to process compeleted requests
request.onreadystatechange = function () {
// Only run if the request is complete
if (request.readyState !== 4) return;
// Process the response
if (request.status >= 200 && request.status < 300) {
// If successful
resolve(request);
} else {
// If failed
reject({
status: request.status,
statusText: request.statusText
});
}
};
// Setup our HTTP request
request.open(method || 'GET', url, true);
// Send the request
request.send();
});
};
makeRequest('https://some-url.com/posts')
.then(function (posts) {
console.log('Success!', posts);
})
.catch(function (error) {
console.log('Something went wrong', error);
});
我想问的第一个问题是关于 then() 的回调,我的意思是我们在 then() 中使用的回调,比如 then( (data)=>{console.log(data)})。能不能把它想象成我们在promise之前使用的异步回调,也就是一直等待到异步的回调,比如xhr对象完成返回结果。并且,在 promise 中 then() 的回调等待直到 promise 给出结果,这意味着 Promise 有助于将回调函数与异步操作分离。第二个问题,then() 的回调是异步的,我的意思是,它是否也通过事件循环以及承诺包装的异步代码或承诺包装的代码(例如 xhr 对象)运行,是承诺中唯一的异步吗?第三个问题,当我们说函数返回promise的时候,是不是说promise不管有没有resolved都会马上返回。当函数返回承诺时,我能想象这样吗,返回的承诺有点告诉我们“
解决方案
我可以把
then
回调想象成一个异步回调,就像我们在 Promise 之前使用的那样吗?
是的。它仍然“只是”一个回调,当 xhr 对象完成并获得其结果时,它会被异步调用。
Promise 有助于将回调函数与异步操作解耦
对,就是这样。您不再需要知道结果的确切来源以及如何获得它 - 您只需有一个承诺并可以使用它来等待结果。
当一个函数返回一个 Promise 时,返回的 Promise 有点告诉我们“请稍等,我保证我会为您提供可以使用 then() 处理的结果”
恰恰。
我的意思是异步的回调
then()
是否也通过事件循环运行?
是的。除了 XHR 异步解决 promise 之外,所有then
回调都保证被异步调用。
当我们说一个函数返回一个promise时,这是否意味着无论它是否被resolve,promise都会立即返回?
是的。这是一个可观察的句柄。
推荐阅读
- c# - 在生产环境中使用 Fluent Asserts 增强默认的 .NET LINQ 不良异常?
- oauth-2.0 - 如何使用 Keycloak Server 内省来自公共客户端的 access_token?
- android - queryIntentActivities 使用相同的代码返回不同的结果
- jenkins - 当构建队列被取消时,有没有办法发送电子邮件?
- karate - 标记或值放在带有额外括号的 var 中
- typescript - 带有任意数量参数的函数,后跟 TypeScript 中的回调
- python - 无法正确地将 pandas 索引转换为日期时间
- powershell - Invoke-RestMethod : 通用传入 webhook 接收到错误的有效负载
- sql-server - MSSQL 2012 - 在表格、数据透视表中逐小时跟踪零件编号?
- javascript - html表单内的模态