Node.js: What parts of the code are executed after an asynchronous call?

Asynchronous calls are an integral part of javascript, and using callbacks is often an elegant tool to handle these calls.

However, I am not quite sure how code branching was decided after an asynchronous operation. For example, what will happen to the following code?

function f(callback) {
   value = some_async_call();
   if (value) {
       callback(value);
   }
   return(value);
}

What will be here? From my short experience, JS returnwill send back the value undefined. But suppose it valuereturns true from an asynchronous call, will the callback be called with the correct value or value undefined?

In other words, is there a rule regarding which operations are performed immediately after the asynchronous call and which are deferred until the value is returned?

,

SFTW javascript, .

+6
2

, undefined . , . , async/await . , some_async_call returns Promise :

async function f(callback) {
  var value = await some_async_call();
  if (value) {
    callback(value);
  }
  return value;
}

Promise, . .

. await .

, , async/await, - some_async_call , value as:

function f(callback) {
 some_async_call(function(value) {
   if (value) {
     callback(value);
   }
 });
}

, async, Promise. Observable RxJS.

+3

:

, some_async_call(); : async function some_async_call() { ... }

, Promise, , value : value.then( function(result) { } )

:

async function some_async_call() { 
    if (theMoonIsInTheRightPosition)
        return Fetch('/api/data/') // this returns a promise as well.

    return false;
}

2 :

function parentFunction(callback) {
    var promise = some_async_call();
    promise.then( callback );
    return ...; // you can't "return" the value of an async call synchronously, since it is a promise.
}

async function asyncParentFunction( callback ) {
    var value = await some_async_call();
    if (value)
        callback( value );
    return value;
}

, , ... .

:

, promises, async/await

function doStuff(callback) {
    // do asynchronous stuff
    var result = 100;
    callback(result); // once you're done with stuff
}
doStuff( function(data) { console.log('Im done!', data); } );

promises

function doStuff() {
    return new Promise(function(resolve, reject) {
        // do asynchronous stuff
        var result = 100;
        resolve(result);
    });
}
doStuff.then(function(data) { console.log('Im done!', data); });

/Await

function doStuff() {
    return new Promise(function(resolve, reject) {
        // do asynchronous stuff
        var result = 100;
        resolve(result);
    });
}
(async function() { // async/await only works in async functions.
    var data = await doStuff();
    console.log('Im done!', data);
})();

: promises async/await .

:

function fetchUserWithPosts(userId, callback) {
    fetchUser(userId, function(user) {
        fetchPostsByUserId(userId, function(posts) {
            callback({
                user: user,
                posts: posts
            });
        });
    });
}

promises

function fetchUserWithPosts(userId) {
    return Promise.all([
        fetchUser(userId),
        fetchPostsByUserId(userId)
    ]).then(function(result) {
        return {
            user: result[0],
            posts: result[1]
        };
    });
}

/Await

async function fetchUserWithPosts(userId) {
    return {
        user: await fetchUser(userId),
        posts: await fetchPostsByUserId(userId);
    };
}
+3

Source: https://habr.com/ru/post/1016600/


All Articles