函数调用如何解决承诺?
How promise is resolved by function call?
我找到了这个 promise 片段,我可以在 Promise.race() 中使用它来防止等待长时间的异步操作,如果我的一些并行代码可以更快地完成的话。
let stopCallback = null;
const stopPromise = new Promise(x => stopCallback = x);
await stopPromise; // promise pending until stopCallback() will be executed somewhere
但是我不能完全理解这个 Promise 到底是如何工作的。
有人可以向我解释这个承诺是如何解决的,或者给出任何 link 详细描述此类用例的地方吗?
Promise 有 2 个回调函数。
1) 解决和 2) 拒绝
let stopCallback = null;
const stopPromise = new Promise((resolve,reject) => {
// call here resolve or reject ,by this promise exexution will be completed
// resolve('data') or reject('data')
});
(async () => {
const resolvedOrRejectedData = await stopPromise;
})
如果您不 resolve 或 reject promise,那么它将保持 pending 状态。
IMO 如果你叫 x
另一个名字会更清楚:
let stopCallback = null;
const stopPromise = new Promise( resolve => stopCallback = resolve);
事实上,无论何时调用 stopCallback()
,它都等同于调用 resolve()
并解析 Promise。
实际上,Promise 只是回调的包装器。它可以(或多或少)写成:
class Promise {
_resolved = undefined;
_handlers = [];
constructor(callback) {
callback(function resolve(value) {
this._resolved = value;
this._handlers.forEach(h => h(value));
}, /*reject*/);
}
then(handler) {
if(this._resolved) handler(this._resolved);
this._handlers.push(handler);
// return new Promise(...);
}
}
换句话说:如果您调用 promise.then(callback)
,那么 callback
将存储在 promise 中。然后,当您调用 promise 的 resolve()
时,它会遍历所有存储的回调并调用它们。
现在 await stopPromise;
根据该承诺调用 .then(...)
,并将一个内部函数传递给它,当被调用时恢复当前 async function
的执行。然后它停止执行该函数。因此,如果您通过回调解决您的承诺,所有 .then(...)
回调都会被调用,包括在异步函数中注册的回调,然后继续执行 async function
.
我找到了这个 promise 片段,我可以在 Promise.race() 中使用它来防止等待长时间的异步操作,如果我的一些并行代码可以更快地完成的话。
let stopCallback = null;
const stopPromise = new Promise(x => stopCallback = x);
await stopPromise; // promise pending until stopCallback() will be executed somewhere
但是我不能完全理解这个 Promise 到底是如何工作的。
有人可以向我解释这个承诺是如何解决的,或者给出任何 link 详细描述此类用例的地方吗?
Promise 有 2 个回调函数。 1) 解决和 2) 拒绝
let stopCallback = null;
const stopPromise = new Promise((resolve,reject) => {
// call here resolve or reject ,by this promise exexution will be completed
// resolve('data') or reject('data')
});
(async () => {
const resolvedOrRejectedData = await stopPromise;
})
如果您不 resolve 或 reject promise,那么它将保持 pending 状态。
IMO 如果你叫 x
另一个名字会更清楚:
let stopCallback = null;
const stopPromise = new Promise( resolve => stopCallback = resolve);
事实上,无论何时调用 stopCallback()
,它都等同于调用 resolve()
并解析 Promise。
实际上,Promise 只是回调的包装器。它可以(或多或少)写成:
class Promise {
_resolved = undefined;
_handlers = [];
constructor(callback) {
callback(function resolve(value) {
this._resolved = value;
this._handlers.forEach(h => h(value));
}, /*reject*/);
}
then(handler) {
if(this._resolved) handler(this._resolved);
this._handlers.push(handler);
// return new Promise(...);
}
}
换句话说:如果您调用 promise.then(callback)
,那么 callback
将存储在 promise 中。然后,当您调用 promise 的 resolve()
时,它会遍历所有存储的回调并调用它们。
现在 await stopPromise;
根据该承诺调用 .then(...)
,并将一个内部函数传递给它,当被调用时恢复当前 async function
的执行。然后它停止执行该函数。因此,如果您通过回调解决您的承诺,所有 .then(...)
回调都会被调用,包括在异步函数中注册的回调,然后继续执行 async function
.