JQuery Deferred: синхронно ждать результатаJquery

Программирование на jquery
Ответить
Гость
 JQuery Deferred: синхронно ждать результата

Сообщение Гость »


I have a function that is called when the user navigates away from a page. This function ensures that pending changes on the page are always saved. If saving fails, the navigation can be cancelled by returning false from this method. This is existing code in the application and cannot be changed to work with callbacks (legacy).

This method is used an OnClick-handler for navigation elements (I know, legacy):

link Now I have this new function that uses jQuery.Deferred to save changes on a page. I want to call this functionality from the method described above, but due to the synchronous nature of that method, I cannot use a callback.

How can I 'wait' for the result of a jQuery.Deferred in this context?

Here some pseudocode (and as a fiddle):

function saveAll() { var d = $.Deferred(); //Do work asynchronously and cann d.resolve(true); setTimeout(function(){ console.log("everything is saved.") d.resolve(true); }, 1000); return d; } function saveOnNavigation() { if(saveAll()){ console.log("saved and navigate to next page."); return true; } console.log("failed to save. Staying on page"); return false; } var x = saveOnNavigation(); if(x === true) { console.log("navigating to next page"); } The output is now:

saved and navigate to next page. navigating to next page everything is saved. While it should be:
everything is saved. saved and navigate to next page. navigating to next page

Источник: https://stackoverflow.com/questions/408 ... chronously
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Jquery»