pomo651 / algo

0 stars 0 forks source link

[Dropbox面经][Javascript] 首先实现一个myPromise class #18

Open pomo651 opened 3 years ago

pomo651 commented 3 years ago
function backEnd() {
    if(Math.random() > 0.5) {
    return {
        status: 200,
      user: {
        name: "Eason",
        email: "eason@gmail.com",
        phone: 1234
      }
    }
  } else {
        return {
        status: 400,
      error: {
        message: "timeout"
      }
    }  
  }
}

function mockApiCall() {
*   return new Promise((resolve, reject) => {  
    setTimeout(() => {
        const response = backEnd();
      if(response.status === 200) {
        resolve(response);
      } else if(response.status === 400) {
        reject(response);
      }
    }, 2000)
  })
}

const mockApiCallPromise = mockApiCall();
mockApiCallPromise
    .then(res => console.log(res.user))
  .catch(err => console.log(err.error.message));

要求:

1.上面给出了一个测试用例,此时例子 line with * 是用的 JS 原生 new Promise()...

先把上面code拿到JS Fiddle里面跑下,知道在做什么.

2.现在要求写一个简单版本的 class myPromise { }

如果写的成功的话,那么 line with * 如果替换成: return new myPromise((resolve, reject) => { 也会得到同样的结果,则算是pass test cases.