Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

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

Open
Sunny-117 opened this issue Nov 3, 2022 · 5 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);
    }),
  ]);
}

@linlai163
Copy link

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

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

No branches or pull requests

6 participants