Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

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

Open
Sunny-117 opened this issue Nov 3, 2022 · 6 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@weirong111
Copy link

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

@rpqp
Copy link

rpqp commented Mar 14, 2023

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
Copy link

cscty commented Jun 18, 2023

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

@huxuedong
Copy link

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
Copy link

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

@jianxingyao
Copy link

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

不知道是不是这个意思

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants