Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate all jQuery $.Deferred promises to native ES6 Promise #82

Open
Raruto opened this issue Jul 22, 2022 · 0 comments · May be fixed by #308
Open

Migrate all jQuery $.Deferred promises to native ES6 Promise #82

Raruto opened this issue Jul 22, 2022 · 0 comments · May be fixed by #308
Labels
help wanted Extra attention is needed
Milestone

Comments

@Raruto
Copy link
Collaborator

Raruto commented Jul 22, 2022

Example 1 — Cleaning up a simple .then() and .fail()

// Before
function bar() {
 foo()
 .then(function() {
   console.log("Success");
 })
 .fail(function() {
   console.log("Error");
 });
}
// After
async function bar() {
 try {
   await foo();
 console.log("Success");
 } catch {
   console.log("Error");
 }
}

Example 2 — Cleaning up .then() and .fail() callbacks

// Before
function bar() {
 executeFoo(function() {
   console.log("Success");
 },
 function() {
   console.log("Error");
 });
}

function executeFoo(successCallback, errorCallback) {
 foo()
 .then(successCallback)
 .fail(errorCallback);
}
// After
async function bar() {
 try {
   await foo();
   console.log("Success");
 } catch {
   console.log("Error");
 }
}

Example 3 — Migrating $.Deferred() notifications

// Before
function notifyEvery500MS (progressCallback) {
 const deferred = $.Deferred();
 let count = 0; const interval = setInterval(function () {
   if (count === 10) {
     clearInterval(interval);
     deferred.resolve();
   }
   else {
     count += 1;
     deferred.notify(progressCallback);
   }
 }, 500);
 return deferred;
}
// After (a bit more involved)
function notifyEvery500MS (progressCallback) {
 let count = 0; const interval = setInterval(function() {
   window.dispatchEvent(new CustomEvent("notify", {detail: count}));
   count += 1; 
 }, 500);return Promise.resolve({then: function(onfulfilled) {
   window.addEventListener("notify", function notifyListener(e) {
    if (e.detail === 10) {
       clearInterval(interval);
       window.removeEventListener("notify", notifyListener);
       onfulfilled();
    }
    else {
      progressCallback();
    }
   });
 }});
}

Source: https://medium.com/@szpytfire/migrating-from-jquery-to-es6-promises-65ee10553126


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
1 participant