我正在阅读 YDKJS 系列的《异步与性能》一书,但无法理解揭示的构造函数模式。
这是本书给出的示例:
function foo(x) {
// start doing something that could take a while
// construct and return a promise
return new Promise( function(resolve,reject){
// eventually, call `resolve(..)` or `reject(..)`,
// which are the resolution callbacks for
// the promise.
} );
}
var p = foo( 42 );
function bar(fooPromise) {
// listen for `foo(..)` to complete
fooPromise.then(
function(){
// `foo(..)` has now finished, so
// do `bar(..)`'s task
},
function(){
// oops, something went wrong in `foo(..)`
}
);
}
bar( p );
我有两个问题:
我认为这样做的目的是不向外部公开解析和拒绝逻辑,这样可以很好地分离 Promise 逻辑和
.then() 接下来发生的事情之间的关注点
在“监听” Promise 的函数(在本例中为bar()
)中。我走上正轨了吗?示例
foo()
让我感到困惑。在注释//start do something that might take a while
中,这到底是什么?这是你的异步调用的地方吗?它不应该在 return 语句中的函数内部吗?我不明白这会如何工作。
最佳答案
I think the intention is not to expose the resolve and reject logic to the outside, which creates a good separation of concern
是的,这以及在 deferred pattern 中捕获异常的困难,另一种方法是仅向创建任务的函数公开解析器,而不向使用结果的函数公开解析器。
The example
foo()
confuses me. In the comment// start doing something that could take a while
, what exactly is this? Is this where your async call would be?
是的,他们就是这个意思。
Shouldn't it be inside the function in the return statement?
是的,确实应该如此。一个具体的例子可能是
function delay(x) {
return new Promise(function(resolve) { // construct and return a promise
setTimeout(function() { // start doing something that could take a while
resolve(); // eventually, call one of the resolution callbacks
}, x);
});
}
当然有可能启动任务和等待其结果是两个单独的语句,因此理论上它们可以分开:
function ajax(x) {
var xhr = new XMLHttpRequest();
xhr.open("GET", x);
xhr.send(); // start doing something that could take a while
return new Promise(function(resolve, reject) { // construct and return a promise
xhr.onload = resolve;
xhr.onerror = reject; // eventually, call one of the resolution callbacks
});
}
但这是一个不好的做法,因为当new
、open
或send
抛出时你不会得到一个被拒绝的 promise ,但一个异常(exception)。因此 var xhr = ...
中的所有内容都应该位于 Promise 构造函数回调内。
关于javascript - JS Promise 在 YDKJS 中揭示构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45330089/