在 Node js 中使用 setTimout() 作为 Promise

我是 JS 新手,我正在 Node.js 中为我的应用程序编写一些简单的 REST API。在代码中的某个地方,我想等待大约 5 秒钟。


我对使用 Promise 和正常超时方法感到困惑,并在其他地方调用该函数。如下:


const sleep = (time) => {

    return new Promise(resolve => {

        setTimeout(() => {

            resolve()

            console.log('5 seconds');

        }, time);

    })

}

然后调用函数:


sleep(5000)

或者


const sleep = (time) => {

    return new Promise(resolve => {

        setTimeout(() => {

           resolve()

           console.log('5 seconds');

       }, time);

    })

}

然后调用函数:


sleep(5000).then(() => console.log('5 seconds passed'))

或者


const sleep = (time) => {

    return new Promise(resolve => {

        setTimeout(() => {

            resolve()

            console.log('5 seconds');

        }, time);

    })

}


async function wait(sleepTime) {

    await sleep(sleepTime)

}

然后调用函数:


wait(5000)

难道我做错了什么?因为在所有 3 种情况下,我实际上得到了 5 秒的等待时间,但是由于函数返回 Promise,我必须使用.then()If I want to use the Promise。


喵喔喔
浏览 156回答 3
3回答

绝地无双

然后当你想获得 promise 的结果时使用,即使不使用它的结果,promise 的代码仍然可以工作

LEATH

更新:在第 3 种情况下,您可以await使用async函数。(async () => {  await wait(5000);  // Do something after 5 sec})();您的代码没有任何问题。所以我不确定你的问题是什么。不管怎样,你可以这样理解Promise:new Promise(resolve => {  setTimeout(() => {    resolve();  }, 5000);}).then(() => {  // Do something after 5 sec });相当于setTimeout(() => {  // Do something after 5 sec}, 5000);

jeck猫

第一种情况。1.异步执行,doSomething()不等待sleep函数完成执行。2. 承诺将保持挂起状态。sleep(5000); doSomething();// execution starts without waiting for 5 seconds.第二种情况:1.Promise 已解决,then()/catch()侦听器被调用。2.doSomething()执行sleep()完成后执行。sleep(5000).then(() => {doSomething();// execution starts after waiting for 5 seconds. })第三种情况:1. Async 函数返回一个promise。2. 等待/然后 - 以相同的方式工作(解决/拒绝承诺并返回数据/错误)。3. Await 只能在 async 函数内部使用。我建议您只创建一个包含 api 业务逻辑的异步函数。async function wait(sleepTime) {    // some code     await sleep(sleepTime); // waiting      doSomething(); // execution starts only after waiting.    // some other code}调用waitwithoutthen将导致挂起的承诺,但这不会影响您的业务逻辑。// sample example.wait(5000).then(()=>{res.send("ok");}).catch(e=>{res.send("err")});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript