我想在其中学习如何处理异步代码的 Node js 代码

Node js code in which i want to learn how to tackle asynchronous code

setTimeout(()=>{
        console.log('time out')
    },3000)
}

go();
console.log('app')

这是异步代码,我想在延迟后打印应用程序,但我们知道先打印 "app" 然后 "time out"。

您可以使用 promise 处理异步代码

  function go() {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            console.log('time out');
            resolve()
        },3000)
    })
}

go().then(() => {
    console.log('app')
})

您可以通过两种方式处理异步任务:-

  1. 使用 Promise 然后使用方法
  2. 用async/await方法

第一种方式:-

function promiseFunction() {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            console.log('completed task and resolve');
            resolve()
        },3000)
    })
}
promiseFunction().then(() => {
    console.log('all task completed with your message (app)');
})

第二种方式:-

asyncFunction();
function promiseFunction() {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            console.log('completed task and resolve');
            resolve()
        },3000)
    })
}
async function asyncFunction() {
  await promiseFunction();
  console.log('all task completed with your message (app)');
}

P.S请确保您的 await 关键字应该在异步函数中。