自定义 JavaScript promise

一个油管上的例子:

const setup = () => {
  delay("blah blah")
    .then(() => console.log("Hello"))
    .catch((err) => console.log(err));
};

const delay = (time) => {
  return new Promise((resolve, reject) => {
    if (isNaN(time)) {
      reject(new Error("delay requires a valid number"));
    }
    setTimeout(resolve, time);
  });
};

setup();

MDN:
The Promise.reject() method returns a Promise object that is rejected with a given reason.

function resolved(result) {
  console.log('Resolved');
}

function rejected(result) {
  console.error(result);
}

Promise.reject(new Error('fail')).then(resolved, rejected);
// expected output: Error: fail

你可能感兴趣的:(javascript)