I want to pass each item into a function that take times. But seems that the JS function is asynchronized. How can I call the function sequentially ? (Pass next item to function after the previous done)
function main() {
for (var i = 0; i < n ; i++) {
doSomething(myArray[i]);
}
}
function doSomething(item) {
// do something take time
}
My solution is call the function recusively. But I want to know is there a different way to solve this issue ? Thanks.
function main() {
doSomething(myArray, 0);
}
function doSomething(item, i) {
// do something take time
doSomething(myArray, i + 1);
}
In JavaScript, as of 2020, the for-loop is async/await aware. You can return a promise and then await
that promise inside of the for loop. This causes the loop to execute in a series, even for long running operations.
function randomSleep(ms, seed=10) {
ms = ms * Math.random() * seed;
return new Promise((resolve, reject)=>setTimeout(resolve, ms));
}
async function doSomething(idx) {
// long running operations
const outcome = await randomSleep(500);
return idx;
}
const arrItems = ['a','b','c','d'];
for(let i=0,len=arrItems.length;i<len;i++) {
const result = await doSomething(i);
console.log("result is", result)
}
Read more about async await in for loops and forEach loops here https://zellwk.com/blog/async-await-in-loops/
if you want to pass next item to function after the previous done, you can try to use promise, just like this
var Q = require('q');
var promise;
main();
function main() {
promise = doSomethingPromise(0)
for (var i = 1; i < 10 ; i++) {
(function (i) {
promise = promise.then(function (res) {
return doSomethingPromise(res + ' ' + i)
});
})(i)
}
}
function doSomethingPromise (item) {
var d = Q.defer();
d.resolve(doSomething(item));
return d.promise;
}
function doSomething(item) {
// do something take time
console.log('doSomething', item);
return item;
}
it can make you function to be called by order.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.