gpt4 book ai didi

javascript - 对在 JS 中如何使用 promises 感到困惑

转载 作者:行者123 更新时间:2023-11-30 13:56:33 25 4
gpt4 key购买 nike

我是 JS 的新手,正在学习 promises 以及它们在 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)} )。我可以把它想象成我们在promises之前使用的异步回调,也就是一直等待到异步的回调,比如xhr对象完成并返回result。并且,在 promise 中,then() 的回调会一直等到 promise 给出结果,这意味着 PROMISE 有助于将回调函数从异步操作中分离出来。第二个问题,then() 的回调是异步的,我的意思是,它是否也通过事件循环以及 promise 包装的异步代码运行,或者 promise 包装的代码,例如 xhr 对象,是 promise 中唯一的异步?第三个问题,我们说function returns promise,是不是说promise不管resolved有没有立马返回。当函数返回 promise 时,我能想象这样吗,返回的 promise 有点告诉我们“请稍等,我保证我会为你提供你可以用 then() 处理的结果”

最佳答案

Can I imagine a then callback as an asynchronous callback, like the ones we used before promises?

是的。它仍然“只是”一个回调,在 xhr 对象完成并获得其结果时被异步调用。

PROMISE HELPS TO DECOUPLE CALLBACK FUNCTION FROM ASYNCHRONOUS OPERATION

是的,没错。你不需要再知道结果到底从哪里来以及如何得到它——你只要有一个 promise ,就可以用它来等待结果。

When a function returns a promise, that returned promise kinda tells us "please wait a bit and I promise I will provide you with the result which you can handle with then()"

没错。

Is the callback of then() asynchronous, I mean, is it also run via event loop as well?

是的。除了 XHR 异步解析 promise 之外,所有 then 回调都是 guaranteed to be called asynchronously .

When we say a function returns a promise, does it mean that the promise is returned right away regardless of whether it was resolved or not?

是的。这是一个可观察的句柄。

关于javascript - 对在 JS 中如何使用 promises 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57181754/

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