How to check when a async function has completed its execution through promises?

async/await
async/await vs promises
await promise
async arrow function
async/await fetch
async/await try catch
javascript promise
convert promise to async/await

I have an async function which is being called by another function. I want to perform some action once the async function has completed its execution. I am trying to use promises to do this. I think I am going wrong somewhere in my usage of promises. Here is the code I have:

function foo(){
setTimeout(()=>console.log("hello world"),1000)
}

function bar(){
  return new Promise(function(resolve){
  resolve(foo())
  })
}

bar().then(()=>console.log("foo has completed"))

The console prints "foo has completed" even before the async has completed its execution.

Calling resolve is something you should do yourself. Since foo returns immediately, your promise also get resolved immediately. However, you could do something like below if that fulfills your requirement.

function foo(resolve) {
  setTimeout(() => {
    console.log("hello world");
    resolve();
  }, 1000)
}

function bar() {
  return new Promise(function(resolve) {
    foo(resolve)
  })
}

bar().then(() => console.log("foo has completed"))

JavaScript Promises and Async/Await: As Fast As Possible™, JavaScript executes code in a single thread, which makes it blocking. Using Async/Await syntax, a promise-based asynchronous code can be to its definition is a function which will be called when a job is finished. that's where we know that a() has done its job and similarly call c() in the callback of a . While working with Asynchronous JavaScript, people often write multiple statements one after the other and slap an await before a function call. This causes performance issues, as many times one statement doesn’t depend on the previous one — but you still have to wait for the previous one to complete. An example of async/await hell

If you spend some time looking at javascript you will notice that all async functions have some mechanism for letting you know when they are done. This is typically callbacks or promises, but sometimes other things like events.

Your function foo() performs an async operation, but offers not way to alert the caller or anyone else when it's done. That's what is causing your problem, and there's no good way to fix it without changing foo(). Here are some things you can do.

Have foo call a callback

You could change foo() to call a callback when it's finished. Then it might look like this:

 function foo(cb){
    setTimeout(()=>{
        console.log("hello world")
        cb(null, true) // callbacks offen pass an error as their first arg or null if there's no error

    },1000)
}

With that, bar() can call it passing a callback and then either fire a callback or return a promise. Here we'll return a promise and wire it all together:

function foo(cb){
    console.log("foo called")
    setTimeout(()=>{
        console.log("foo's timeout finished")
        cb(null, true)

    },1000)
}
    
function bar(){
    console.log("car called")
    return new Promise((resolve, reject) =>{
        foo((err, res) => {
            if (err) return reject(err)
            resolve( "foo finished with " + res)
        })
    })
}

bar().then((result)=>console.log("bar has finish and returned: ", result))

JavaScript: Promises and Why Async/Await Wins the Battle, Asynchronous functions are a good and bad thing in JavaScript. sometimes have to wait for one function to complete in order to get its “callback” before proceeding to the next execution. view raw callback.js hosted with ❤ by GitHub Promises provide a simpler alternative for executing, composing and  At their most basic, promises are similar to event listeners, but with a few differences: A promise can only succeed or fail once. It cannot succeed or fail twice and it cannot switch from success to failure or vice versa once the operation has completed.

I think your code should be like this

function foo() {
  return new Promise(function(resolve) {
    setTimeout(() => {
      console.log("hello world");
      resolve();
    }, 1000);
  });
}

function bar() {
  return new Promise(function(resolve) {
    resolve(foo());
  });
}

bar().then(() => console.log("foo has completed"));

Graceful asynchronous programming with Promises, Even if the handleCallButton() function has already returned to the code that called it, when getUserMedia() has finished working, it calls the  Understanding the concepts of Callbacks, Promises, and Async/Await can be rather confusing, but so far we have seen how they work when carrying out asynchronous operations in JavaScript. They come in handy a lot when making API requests and event handling. You can learn more about using promises here and async functions here. Like this article?

You are returning a setTimeout() call in the resolve call. This should fix it:

function foo(resolve){
setTimeout(()=> { 
  console.log("hello world");
  resolve()
 },1000)
}

function bar(){
  return new Promise(function(resolve){
    return foo(resolve)
  })
}

bar().then(()=>console.log("foo has completed"))

Async/await, works only inside async functions let value = await promise ; The function execution “pauses” at the line (*) and resumes when the the built-in functions resolve and reject as arguments (just as it does for a regular Promise executor). Then await waits until one of them is called (in the example above it  Note: Async/Await is slightly slower due to its synchronous nature. You should be careful when using it multiple times in a row as the Await keyword stops the execution of all the code after it

Deeply Understanding JavaScript Async and Await with Examples, A callback is nothing special but a function that is executed at some later time. Due to It is important to note the async functions work on top of promises. They are not a Let's see the usage of await and return together — async function foo​() { Maybe you want to complete promises in batches. You can  To indicate that a function has completed its work successfully, the promise should be resolved. To indicate an error, the promise should be rejected. This means you only need to handle errors that

Async functions, Async functions allow you to write promise-based code as if it were synchronous. When you await a promise, the function is paused in a non-blocking way until Note: If you're unfamiliar with promises, check out our promises guide. It won'​t wait for the first function to complete before calling the second. Asynchronous recursion with async / await. The purpose of async functions is to simplify the use of promises. As you’ve seen in the previous example, moving a very simple function from synchronous to asynchronous has a significant effect on code complexity, and with our recursive example, both callbacks and promises are quite messy.

Asynchronous work, Jasmine will wait until the returned promise is either resolved or rejected Note that in order to use async / await you need to either run your tests in a pass a function to be invoked when asynchronous work has been completed. callback​-style asynchronous tests is to call done when the code under test is still running. Start Multiple Async Tasks and Process Them As They Complete (C#) 09/12/2018; 5 minutes to read +9; In this article. By using Task.WhenAny, you can start multiple tasks at the same time and process them one by one as they’re completed rather than process them in the order in which they're started.

Comments
  • foo() returns BEFORE it is done with its timer because setTimeout() is asynchronous and non-blocking. The problem is in foo(). Promises or resolve() have no magic powers to somehow know when an async operation in them is done. You have to ONLY call resolve() when the asynchronous operation is actually done. You're calling it before the async operation is done. Thus, the promise triggers before the async operation is done.
  • This is a weird way to program with promises. foo() should just return its own promise.
  • 2nd option > 1st option. Promisifying at the lowest level practical is preferred.
  • @jfriend00 agreed.
  • Why mark a function async if you don't use await in it
  • No reason to create a new promise in bar(). You can just do return foo() inside of bar(). And, no reason to use async keyword at all.
  • This is a weird way to program with promises. foo() should just return its own promise.
  • @jfriend00, functions are the first class citizens and could be passed around any way you want. I think you're applying personal patterns that are not related to the problem domain. You can look at the resolve param as a callback, and that may change your prospective
  • I didn't say it doesn't work, but it's not common to pass around a reference to resolve and not recommended either. That's why the promise specification doesn't have deferred objects, only promises with the promise executor. Anyone who programs with promises regularly would tell you that foo should just return its own promise here. That's the cleaner promise design. Yes, all of design is an opinion, but when most people educated on the topic would have the same opinion about a design, that's a common and accepted design pattern.
  • Looking at it as callback means you're mixing promises and callbacks which is a bad design decision. It just complicates everything. Good promise design promisifies async operations at the lowest level and then uses only promise flow control management. I rather doubt you're going to win any argument that this is a preferred design and that's what my first comment is about.
  • I agree with @jfriend00 - it's a little strange although not that much different than passing a callback to foo. The real difficulty comes in a more realistic scenario where you wanted to account for the possibility that foo could have an error. So then you would have to pass both resolve and reject functions into foo. But that's not the way most callback-based functions work -- they prefer the callback(err, result) pattern. Which leaves you with a foo that doesn't work the way most people would expect it to, which leads to bugs.