var myFunc = function(){ var test = 0; setTimeout(function(){ test = 10; }, 5000); return test; } alert(myFunc()); How to get result 10 without using yield
var myFunc = function(){ var test = 0; setTimeout(function(){ test = 10; }, 5000); return test; } alert(myFunc()); How to get result 10 without using yield
And if you use async / await from ES7, you can do this:
const myFunc = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(10); }, 5000); }); }; (async function() { alert(await myFunc()); })(); And here is a working example on JSFiddle.
Yes, the definition of the myFunc function myFunc become more difficult. However, using async / await, we can write pseudo-sync code without explicitly using Promises and Generators . For example:
let updatePost = async function(uid, pid, newBody) { let user = await loadUser(uid), post = await loadPost(pid), canEdit = await user.canEdit(post); if (!canEdit) { return false; } post.setBody(newBody); await post.save(); return true; }; But there is bad news. ES7 is not only not supported by browsers, but is not even accepted as standard. Although all the code above is well transported through Babel , browser native support is still far away.
ES2017 to the standard by ES2017 , and then - if you're lucky. Now it is - just a superstructure above the language. - user207618setTimeout(resolve, 5000, 10); :) - Qwertiy ♦async/await will enter the standard. Painfully beautiful idea. And if so, then you need to prepare now. Moreover, this functionality is already in the Edge out of the box: kangax.imtqy.com/compat-table/esnext/#test-async_functions - Dmitriy SimushevIf I correctly understood the condition of the problem.
var myFunc = function(f) { var test = 0; setTimeout(() => { test = 10; f(test); }, 5000); } myFunc(alert); f(10); is easier right away f(10); without unnecessary variables - GrundyMaybe in the Promise wrap?
var test = 0; (new Promise( function( resolve){ window.setTimeout( function(){ test = 10; resolve(test); }, 3000); })) .then( function(v){ alert(v); }) ; The event variant may also be convenient. Since you have a question about asynchronous interaction, the pub-sub model is relevant.
In the example of an event we listen and throw out on the window object:
var myFunc = function() { setTimeout(function() { window.dispatchEvent(new CustomEvent('ololo', { // в свойстве "detail" можно передать любые данные - // объект с кучей данных, или просто скалярное значение 'detail': { myTestData: 5, moreData: "trololo" } })); }, 2000); } window.addEventListener( 'ololo', function(e) { alert('' +e.detail.myTestData +' ' +e.detail.moreData); }, false ); myFunc(); Source: https://ru.stackoverflow.com/questions/524835/
All Articles