Files
Nicholas Carrigan (he/him) 3da4be21bb chore: seed chinese traditional (#42005)
Seeds the chinese traditional files manually so we can deploy to
staging.
2021-05-05 22:43:49 +05:30

2.2 KiB
Raw Permalink Blame History

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
5cdafbc32913098997531680 通過 resolve 和 reject 完成 Promise 1 301196 complete-a-promise-with-resolve-and-reject

--description--

Promise 有三個狀態:pendingfulfilledrejected。 上一個挑戰裏創建的 promise 一直阻塞在 pending 狀態裏,因爲沒有調用 promise 的完成方法。 Promise 提供的 resolvereject 參數就是用來結束 promise 的。 Promise 成功時調用 resolvepromise 執行失敗時調用 reject 如下文所述,這些方法需要有一個參數。

const myPromise = new Promise((resolve, reject) => {
  if(condition here) {
    resolve("Promise was fulfilled");
  } else {
    reject("Promise was rejected");
  }
});

上面的示例使用字符串作爲這些函數的參數,但參數實際上可以是任何格式。 通常,它可能是一個包含數據的對象,你可以將它放在網站或其他地方。

--instructions--

使 promise 可以處理成功和失敗情況。 如果 responseFromServertrue,調用 resolve 方法使 promise 成功。 給 resolve 傳遞值爲 We got the data 的字符串。 如果 responseFromServerfalse 使用 reject 方法並傳入值爲 Data not received 的字符串。

--hints--

if 條件是 true 時應該執行 resolve

assert(
  code.match(/if\s*\(\s*responseFromServer\s*\)\s*{\s*resolve\s*\(\s*('|"|`)We got the data\1\s*\)(\s*|\s*;\s*)}/g)
);

if 條件是 false 時應該執行 reject

assert(
  code.match(/}\s*else\s*{\s*reject\s*\(\s*('|"|`)Data not received\1\s*\)(\s*|\s*;\s*)}/g)
);

--seed--

--seed-contents--

const makeServerRequest = new Promise((resolve, reject) => {
  // responseFromServer represents a response from a server
  let responseFromServer;

  if(responseFromServer) {
    // Change this line
  } else {  
    // Change this line
  }
});

--solutions--

const makeServerRequest = new Promise((resolve, reject) => {
  // responseFromServer represents a response from a server
  let responseFromServer;

  if(responseFromServer) {
    resolve("We got the data");
  } else {  
    reject("Data not received");
  }
});