封装一个工具函数输入一个promiseA返回一个promiseB如果超过1s没返回则抛出异常如果正常则输出正确的值。
Sunny-117 opened this issue · 5 comments
Sunny-117 commented
封装一个工具函数输入一个promiseA返回一个promiseB如果超过1s没返回则抛出异常如果正常则输出正确的值。
weirong111 commented
function promiseUtil(promise) {
return Promise.race([
promise,
new Promise((_, reject) => {
setTimeout(() => {
reject("error");
}, 1000);
}),
]);
}
linlai163 commented
function timeoutPromise(promise, timeout) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`Promise timed out after ${timeout} ms`));
}, timeout);
promise
.then((result) => {
clearTimeout(timer);
resolve(result);
})
.catch((error) => {
clearTimeout(timer);
reject(error);
});
});
}
cscty commented
function timeout(promise, delay) {
let p = new Promise((resolve, reject) => {
setTimeout(() => {
reject();
}, delay);
});
return Promise.race([promise, p]);
}
huxuedong commented
function getPromise(delay) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('finished')
}, delay)
})
}
function fn(promise) {
return new Promise((resolve, reject) => {
Promise.resolve(promise).then(resolve, reject)
setTimeout(() => {
reject('已经超时了')
}, 1000)
})
}
fn(getPromise(0))
seriouslym commented
let timeout = (promise) => {
return new Promise((resolve, reject) => {
let data = null, err = null;
promise.then(response => {
data = response;
}, reason => {
err = reason
})
setTimeout(() => {
if (err) {
reject(err)
}
if (!data) {
reject(new Error("超时"))
}
resolve(data)
}, 1000)
})
}