How to create own async work in the promise body?

async/await
convert promise to async/await
async/await promise
async/await vs promises
javascript promise example
async arrow function
promise then
javascript promise w3schools

I write the function which emulated big work. I need to get the output:

Work started.
Hello!
Work done.
Bob

This is my "Hello World" example:

function bigWork(user){
    console.log('Work started.');
    const p = new Promise(resolve => {

        setTimeout(() => {
            // here is some long calculatin must
            // be done async. Therefore I placed
            // it inside of setTimeout() function
            for(let n = 0; n < 100000; n++);

            console.log('Work done.');
            resolve(user);
        },0);
    });
    return p;
}

bigWork({name:'Bob', age:30}).then(user=> console.log(user.name));
console.log('Hello!');

You can use Promise.resolve:

function bigWork(user){
    console.log('Work started.');
    return Promise.resolve().then(() => {
        for(let n = 0; n < 100000; n++);
        console.log('Work done.');
        return user;
    });
}

bigWork({name:'Bob', age:30}).then(user=> console.log(user.name));
console.log('Hello!');

Graceful asynchronous programming with Promises, Note: The way that a .then() block works is similar to when you that the response body is fully downloaded, and when it is Each call to .then() creates a new promise. The code inside the function body is async and promise-based, therefore in effect, the entire function acts like a promise — convenient. Next, we call our function three times to begin the process of fetching and decoding the images and text and store each of the returned promises in a variable.

I'm sorry to break it to you, but JavaScript is technically single threaded.

The reason it seems to work for you is because setTimeout code occurs only once the main "thread" is complete, so while your loop is blocking the javascript, your sample application doesn't really show that it is happening.

What you can do is use WebWorkers, which will achieve the multithreading you want, but is a whole beast in and of itself https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API

Making asynchronous programming easier with async and await , Let's look back at a simple fetch example image.src = objectURL; document.​body. of promises and how they work, but let's to create an async function to define a  An async function is a function declared with the keyword async and therefore compiled such that the return value of the function is an implicit (i.e. unnamed) promise which, upon resolution, will provide the value returned by the "apparent" function. The promise (like any promise) will complete in a stack frame different from, and later than, the stack frame in which it was created. Therefore

As far as I understand, you want something like below.

  async function bigWork(user){
    console.log('Work started.');
    const p = await longCalculation(100, user);
  	console.log('Work done.');
    return p;
}

function longCalculation(round, user){
     return new Promise((resolve) => {
     	for(let n = 0; n < round; n++);
       resolve (user);
     })
}

bigWork({name:'Bob', age:30}).then(user=> console.log(user.name));
console.log('Hello!');

Async functions, Human boy working on web standards at Google. Async functions are They make your asynchronous code less "clever" and more readable. Async functions When you await a promise, the function is paused in a non-blocking way until the promise settles. const reader = response.body.getReader(); Lightning Web Components enables the developer to make use of both promise-based asynchronous functionality and the async/await functionality. The only advice now is for developers creating features for users on Internet Explorer 11, async/await is not implemented in that browser. Don’t worry, though, your code will work.

Improve async programming with JavaScript promises, A JavaScript promise can be created using the Promise constructor. to create a fulfilled promise with the value and then work with the classList = 'img img--fluid​'; // Append the image to the document document.body. Promises allow you to create handlers that deal with the eventual success or failure of an asynchronous action. Native promises Fetch Before we'll start rolling our own promises, let's have a look on how to work with a promise that is already available in your browser, natively!

Async/await, There's a special syntax to work with promises in a more comfortable fashion, called Also we should make the function async for them to work. className = "promise-avatar-example" ; document . body . append ( img )  All we need to do to use async await is to create a Promise based delay function. const wait = (ms) => new Promise (res => setTimeout (res, ms)); This function takes a number of milliseconds and returns a Promise that gets resolved using setTimeout after the given number of milliseconds. Now create an async function called startAsync.

Promises chaining, The whole thing works, because a call to promise.then returns a promise, so that we A handler, used in .then(handler) may create and return a promise. Returning promises allows us to build chains of asynchronous actions. className = "promise-avatar-example" ; document . body . append ( img )  Understand promises before you start using async/await. if you understand how promises work, you can get around this by treating the result of an async function as a promise, which itself

Comments
  • No, not if you're emulating the big work with a tight for-loop. That's going to block the thread and prevent anything from happening until it's done running. And if your actual big work is also CPU-bound, you're going to have the same problem and promises are not the solution (at least not the whole solution). You need to look into options for running work on a separate thread. For example, by using web workers.
  • You're emulating async work, but you don't want to use async functions?
  • It is not really multithreading, as WebWorkers are isolated and can only communicate with the main process in a very restricted way. It is more like a isolated child process.
  • True, but the end result is that the code doesn't block, which is the implication of the question... I like the accepted answer for this one. Can't wait for him to come back with a "new" question about why his code doesn't do what he wants lol
  • Hm... I see your code works in the code snippet here, but it doesn't work in Node.js. I get error: ReferenceError: regeneratorRuntime is not defined.
  • Create a test.js file and copy the above code to it. Then in your terminal write "node test.js" and it works on node too.