js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

封装一个工具函数输入一个promiseA返回一个promiseB如果超过1s没返回则抛出异常如果正常则输出正确的值。

Open Sunny-117 opened this issue 2 years ago • 6 comments

Sunny-117 avatar Nov 03 '22 08:11 Sunny-117

function promiseUtil(promise) {
  return Promise.race([
    promise,
    new Promise((_, reject) => {
      setTimeout(() => {
        reject("error");
      }, 1000);
    }),
  ]);
}

weirong111 avatar Nov 06 '22 09:11 weirong111

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);
      });
  });
}

linlai163 avatar Mar 14 '23 12:03 linlai163

function timeout(promise, delay) { let p = new Promise((resolve, reject) => { setTimeout(() => { reject(); }, delay); }); return Promise.race([promise, p]); }

cscty avatar Jun 18 '23 13:06 cscty

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))

huxuedong avatar Jan 17 '24 01:01 huxuedong

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)
    })
}

seriouslym avatar Jan 18 '24 03:01 seriouslym

function gongju(promiseA){
    const promiseB = new Promise((resolve,reject) => {
        promiseA.then(res => {
            resolve(res)
        })
        setTimeout(() => {
            reject(new Error('超时了'))
        }, 1000);
    })
    return promiseB
}
const pA = new Promise((resolve,reject) => {
    setTimeout(() => {
        resolve('成功了')
    }, 1500);
})
gongju(pA).then(res => {
    console.log(res)
},err => {
    console.log(err)
})

不知道是不是这个意思

jianxingyao avatar Sep 15 '24 11:09 jianxingyao