简体   繁体   中英

Node.js How to excecute the below function synchronously

I want to excecute the below function synchronously without change the time and output will be 123.How to do using node.js

function f1(){
  setTimeout(function() {
    console.log('Hi I am order 1');
  }, 3000);
}

function f2() {
  setTimeout(function() {
    console.log('Hi I am order 2');
  }, 2000);
}

function f3() {
  setTimeout(function() {
    console.log('Hi I am order 3');
  }, 1000);
}

f3();
f2();
f1();

Your question seems incorrect, because of functions call order. It looks like you want to call f1() first?.

In 2018 you can use ES6 with async/await:

 let delay = (time) => new Promise((resolve) => setTimeout(resolve, time)) async function f1(){ await delay(3000) console.log('Hi I am order 1') } async function f2() { await delay(2000) console.log('Hi I am order 2') } async function f3() { await delay(1000) console.log('Hi I am order 3'); } void async function run () { // It can be runned one-by-one await f1() await f2() await f3() // Or it can be runned in parallel // And then you lost ordering // await Promise.all([f3(), f2(), f1()]) } () 

A little bit of code refactoring

function f1(){
    console.log('Hi I am order 1');
}

function f2() {
    console.log('Hi I am order 2');
}

function f3() {
    console.log('Hi I am order 3');
}

function delay(func, interval) {
    return new Promise(resolve => {
        setTimeout(() => {
            func();
            resolve();
        }, interval)
    })
}

(async () => {
    await delay(f1, 3000);
    await delay(f2, 2000);
    await delay(f3, 1000);
})();
  • Function f1 , f2 and f3 should only focus on what it does
  • Use delay wrapper to delay the execution
  • Use await to ensure sync execution

JavaScript Promises are the better way to synchronize different functions, however an easier (though harder to maintain) way would be to add an argument to each function that executes whatever function you need to call next.

function f1(func) { setTimeout(function() { console.log('Hi I am order 1'); func(); }, 3000); }

function f2(func) { setTimeout(function() { console.log('Hi I am order 2'); func(); }, 2000); }

function f3(func) { setTimeout(function() { console.log('Hi I am order 3'); func(); }, 1000); }

f1(f2(f3)));

Another way would be to use the setTimeout function itself like so:

function f1() { setTimeout(function() { console.log('Hi I am order 1'); f2(); }, 3000); }

function f2() { setTimeout(function() { console.log('Hi I am order 2'); f3(); }, 2000); }

function f3() { setTimeout(function() { console.log('Hi I am order 3'); }, 1000); }

f1();

However, this method is less flexible if you want to do arbitrary nesting.

Edit: Fixed a mistake in my first example.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM