在 Javascript Promise 中返回 'resolve' 函数
Returning 'resolve' function in Javascript Promise
我在 this blog 中找到了一段代码,它工作得很好,但使用了难以理解的 Promises
export class Mutex {
private mutex = Promise.resolve();
lock(): PromiseLike<() => void> {
let begin: (unlock: () => void) => void = unlock => {};
this.mutex = this.mutex.then(() => {
return new Promise(begin);
});
return new Promise(res => {
begin = res;
});
}
async dispatch(fn: (() => T) | (() => PromiseLike<T>)): Promise<T> {
const unlock = await this.lock();
try {
return await Promise.resolve(fn());
} finally {
unlock();
}
}
}
表达式new Promise(res => { begin = res; })
是否有效? Promise 通常涉及调用 resolve
某事
为什么 const unlock = await this.lock();
解析为函数?
Is it a valid expression? Promises usually involve calling resolve on something ...
是的,它将解析函数存储在全局 begin
变量中。然后当 new Promise(begin)
执行时,它调用 begin
函数并因此解析它。
Why does const unlock = await this.lock(); resolve to a function?
因为 begin
被 new Promise
使用新 Promise (begin(resolve, reject)
) 的 resolve 函数调用。因为 begin 本身就是一个解析器,它会将返回的 Promise 解析为另一个 promise 的解析器函数。
我在 this blog 中找到了一段代码,它工作得很好,但使用了难以理解的 Promises
export class Mutex {
private mutex = Promise.resolve();
lock(): PromiseLike<() => void> {
let begin: (unlock: () => void) => void = unlock => {};
this.mutex = this.mutex.then(() => {
return new Promise(begin);
});
return new Promise(res => {
begin = res;
});
}
async dispatch(fn: (() => T) | (() => PromiseLike<T>)): Promise<T> {
const unlock = await this.lock();
try {
return await Promise.resolve(fn());
} finally {
unlock();
}
}
}
表达式
new Promise(res => { begin = res; })
是否有效? Promise 通常涉及调用resolve
某事为什么
const unlock = await this.lock();
解析为函数?
Is it a valid expression? Promises usually involve calling resolve on something ...
是的,它将解析函数存储在全局 begin
变量中。然后当 new Promise(begin)
执行时,它调用 begin
函数并因此解析它。
Why does const unlock = await this.lock(); resolve to a function?
因为 begin
被 new Promise
使用新 Promise (begin(resolve, reject)
) 的 resolve 函数调用。因为 begin 本身就是一个解析器,它会将返回的 Promise 解析为另一个 promise 的解析器函数。