Promise constructor and (resolve, reject) methods

To convert an existing callback type function to Promise, we have to use the Promise constructor. In the preceding example, ajaxCallPromise returns a Promise, which can be either resolved or rejected by the developer. Let's see how to implement ajaxCallPromise:

const ajaxCallPromise = url => {  return new Promise((resolve, reject) => {    // DO YOUR ASYNC STUFF HERE    $.ajaxAsyncWithNativeAPI(url, function(data) {      if(data.resCode === 200) {          resolve(data.message)      } else {          reject(data.error)      }    })  })}

Hang on! What just happened there? 

  1. First, we returned Promise from the ajaxCallPromise function. That means whatever we do now will be a Promise.
  2. A Promise accepts a function argument, with the function ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.