如果达到超时,如何停止参数中传递的承诺的操作?
don't have cancellation of async functions yet
.
承诺是一种价值,而不是一种行动
,一旦您得到了给定的承诺,我们在JavaScript中就不会有可取消的承诺,因此不可能取消操作。
你唯一能做的就是
the cancellation proposal
写下你的
longRunningFunction
使用令牌:
function longRunningFunction() {
const signal = { requested: false };
async function internal() {
// your regular code here
// whenever you can stop execution:
if(signal.requested) {
return; // and cancel internal operations
}
}
let res = internal();
res.signal = signal;
return res;
}
然后写下你的种族:
export const promiseTimeout = (
promise,
timeoutMs = 10000, //10 secs
message = 'Timeout reached, please try again',
) =>
Promise.race([
promise,
new Promise((resolve, reject) =>
setTimeout(() => {
reject(message);
if (promise.signal) promise.signal.requested = true;
}, timeoutMs),
),
]);