轉換任何其他回撥 API
為了將任何回撥 API 轉換為承諾,假設 promisify 和 promisifyAll 版本不適合 - 你可以使用 promise 建構函式 。
建立承諾通常意味著指定它們何時結算 - 這意味著它們何時轉移到已完成(已完成)或拒絕(錯誤)階段以指示資料可用(並且可以使用 .then 訪問)。
new Promise((fulfill, reject) => { // call fulfill/reject to mark the promise
   someCallbackFunction((data) => {
      fulfill(data); // we mark it as completed with the value
   })
});
舉個例子,讓我們將 setTimeout 轉換為使用 promises:
function delay(ms) { // our delay function that resolves after ms milliseconds
  return new Promise((resolve, reject) => { // return a new promise
    setTimeout(resolve, ms); // resolve it after `ms` milliseconds have passed
  })
}
// or more concisely:
const delay = ms => new Promise(r => setTimeout(r, ms));
我們現在可以像常規的 promise 返回函式一樣使用它:
delay(1000).then(() => console.log("One second passed")).
            then(() => delay(1000)).
            then(() => console.log("Another second passed"));