javascript - promise async await without .then callback -
i trying learn , better understand how promises work new async
/ await
keywords there thing confusing.
in article: https://davidwalsh.name/async-await
it says using async
, await
doesnt require 1 use callback, example:
async function parallel(callback) { const wait1 = wait(500); const wait2 = wait(500); await wait1; await wait2; callback( [wait1, wait2] ); }
if 1 test need define first timeout function serves wait
:
var wait = function(time) { return new promise( function(resolve, reject) { settimeout(function() { resolve( math.random() * time ); }, time); }); };
and need call our parallel
function , read values:
parallel(function(data) { console.log('data', data); });
the problem if read values - promises objects instead of actual values, remedy problem done:
async function parallel(callback) { var wait1 = wait(500).then(function(data) { wait1 = data; }); var wait2 = wait(500).then(function(data) { wait2 = data; }); await wait1; await wait2; callback( [wait1, wait2] ); }
now work, demo here: https://jsfiddle.net/jp3g2q5k/
but me understand why had use .then
callback? supposes callbacks free situation. or maybe knows how alter code work without callbacks.
you resolving promise 'await' keyword. in example be:
const result1 = await wait1; const result2 = await wait2; callback( [result1 , result2 ] );
Comments
Post a Comment