Simplest Way to Wait Some Asynchronous Tasks Complete, in JavaScript

Simplest way to wait some asynchronous tasks complete, in Javascript?

I see you are using mongoose so you are talking about server-side JavaScript. In that case I advice looking at async module and use async.parallel(...). You will find this module really helpful - it was developed to solve the problem you are struggling with. Your code may look like this

var async = require('async');

var calls = [];

['aaa','bbb','ccc'].forEach(function(name){
calls.push(function(callback) {
conn.collection(name).drop(function(err) {
if (err)
return callback(err);
console.log('dropped');
callback(null, name);
});
}
)});

async.parallel(calls, function(err, result) {
/* this code will run after all calls finished the job or
when any of the calls passes an error */
if (err)
return console.log(err);
console.log(result);
});

How to wait for function to finish in javascript?

You can just use async/await for your defined functions, even if you cannot use 'await' keyword outside an async function.

So, for example, you have a index.js file, you can do:


async function main() {
await updateSeason();
await updateFixtures();
}

main()

or invoking directly the function with the short form


(async function main() {
await updateSeason();
await updateFixtures();
})()

Anyway, avoid to use 'writeFileSync' or other 'Sync' functions inside an async function because that block the event loop and decrease your performance.

EDIT: I saw now that you are using Array.prototype.map function with an async callback, that could be the problem.

Try to look here: https://flaviocopes.com/javascript-async-await-array-map/

Or, otherwise, use a standard for loop to handle your leagues

How to wait for all async tasks to finish in Node.js?

Promise are exactly what you need. They're native in JS nowadays, no need for extra libraries.

function finish () {
console.log("finish");
}

function doRequest (uri) {
// wrap code in promise
return new Promise((resolve, reject) => {
request(
{ uri },
(error, response, body) => {
if (error) {
// error case, similar to "throw"
reject(error);
}
else {
// success case, similar to "return"
resolve({ response, body });
}
}
);
});
}

let urls=[...];

// Basic way to do it:
Promise.all(urls.map(doRequest)).then(finish);

// async/await notation:
// you must be in an "async" environement to use "await"
async function wrapper () {
await Promise.all(urls.map(doRequest));
finish();
}
// async function return a promise transparently
wrapper();

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
var value;

// Assume the async call always succeed
async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Wait for asynchronous task to complete before continuing?

Use the callback function for this purpose, do your other job after executed geocoder.geocode(); something like

function getCoords(input_address){
......
......
geocoder.geocode(addr, function (){
doYourJobNow(); //as suggested by tgun926
});

}

function doYourJobNow(){
console.log('should wait');
}

//result would be
//coordinates
//should wait

Better way to wait for a function until next step javascript

You can make your code wait for a timeout to complete by wrapping it in a Promise and using the async await pattern:

// Return a new Promise immediately, that completes at the end of the timeout
function addmessage(element_to_click, element_to_collect) {
return new Promise((resolve, reject) => {
// do whatever

// resolve the Promise after 5s
setTimeout(resolve, 5000)
// you can also resolve the Promise on any other event, like user input
// (or use `reject` when an error occurs)
// you can pass a return value to `resolve` like resolve(input.value)
})
}

// `async` functions also return a Promise immediately
async function addMessages() {
// `await` will block until Promise completes and
// returns the resolved value to be used synchronously within the async func
const in1 = await addmessage('1', '1a')
const in2 = await addmessage('2', '2a')
const in3 = await addmessage('3', '3a')
}

addMessages()

Node.js - Wait for multiple async calls to finish before continuing in code

The simplest way here is to use promises, directly or via async/await syntax. In this case, probably directly.

First, you have to make asyncFunctionCall return a promise. It looks like you always return a boolean, so in this case we'll always resolve the promise:

function asyncFunctionCall(url) {
return new Promise(resolve => {
request(url, function (error, response, body) {
if(typeof response !== 'undefined') {
if((response.statusCode >= 400 && response.statusCode <= 451)
|| (response.statusCode >= 500 && response.statusCode <= 511)) {
resolve(true);
return;
}
}
resolve(false);
});
});
}

Then, build up an array of your promises, and use Promise.all to wait for all of them to complete. These calls run in parallel:

function write(bla) { // gets called one after another
const promises = [];
for(var url in bla) {
promises.push(asyncFunctionCall(url)); // Executed about 50 times.
}
return Promise.all(promises);
}

Then you can build a chain of all of the promises from write so they run in series:

let p = Promise.resolve();
for (const foo in bar) { // <== Notice `const`
// See "Edit" below
p = p.then(() => {
// Here i parse the json object "foo" in the json array "bar"
// bla is an array of multiple urls.
return write(foo[bla]));
});
}

Note that it's important that you use const or let, not var, for foo in that loop, because the then callback closes over it; see this question's answers for why const and let make that work.

Each call to write will only be made when the previous one's work is done.

Then wait for the whole process to complete:

p.then(() => {
// All done
});

You haven't shown anything using the booleans from write's requests, but they're available (as an array) as the resolution value of the promise from write.


The second part of the process, where we're calling write, can also be written in an async function which may make the logical flow clearer:

async function doTheWrites() {
for (const foo in bar) {
// Here i parse the json object "foo" in the json array "bar"
// bla is an array of multiple urls.
await write(foo[bla]);
}
}

Then the overall process:

doTheWrites().then(() => {
// All done
});

...or if this is also in an async function:

await doTheWrites();

Forcing a function to wait until another function is complete

You want to use promises if you have asynchronous code. Promise.all() will wait for them all to be complete before running.

function task1() {  return new Promise(function(resolve, reject) {    console.log("task 1")    setTimeout(function() {      resolve('foo');    }, Math.random() * 2000);  })}
function task2() { return new Promise(function(resolve, reject) { console.log("task 2") setTimeout(function() { resolve('bar'); }, Math.random() * 2000); })}
function task3() { console.log("task 3")}
Promise.all([task1(), task2()]).then(function(values) { console.log(values); task3()});


Related Topics



Leave a reply



Submit