【问题标题】:Building async with setTimeout like a promise with setTimeout doesn't work像使用 setTimeout 的承诺一样使用 setTimeout 构建异步不起作用
【发布时间】:2021-11-09 04:52:39
【问题描述】:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function 他们说写作

async function foo() {
   return 1
}

和写一样

function foo() {
   return Promise.resolve(1)
}

也就是说,如果我们想将一个 Promise '转换'成一个异步函数,我们必须将 resolve(promise_result) 替换为 return promise_result

但是当我尝试将setTimeoutasync 一起使用时,它不起作用:

const test1 = async () => {
    setTimeout(
        () => {
            return 5;
        },
        2000,
    )
}
const test2 = () => new Promise(
    (resolve, reject) => {
        setTimeout(
            () => resolve(25),
            1000
        )
    }
)

const execute = async () => {
    const result = await test1();
    console.log(result); // undefined
}

execute();

如果我在test2 上使用await,它可以工作,但不能在test1 上工作。这是为什么 ? async/await 仅用于处理未决承诺而不使用 .then 还是我可以使用 asyncreturn result 而不是使用 Promiseresolve

【问题讨论】:

  • 您的原始转换仅在您从主函数返回时适用。它不适用于回调函数。
  • setTimeout()回调函数的返回值被忽略。

标签: javascript asynchronous async-await promise


【解决方案1】:

它未定义,因为test1 不会返回任何东西。仔细看看你在匿名函数中返回它回来

const test1 = async () => { // <--- this function returns nothing back. Nothing means "undefined"
    setTimeout(
        () => {       // <---- you return it here back in your anonymous  function witch makes no sense
            return 5;
        },
        2000,
    )
}

【讨论】:

  • 感谢您的评论,我现在明白为什么我得到 undefined 了。但是我如何使用async而不是Promises创建一个使用setTimeout并最终返回一些东西的函数?
  • @David 我猜你不能。使用new Promise 是要走的路
【解决方案2】:

这很有趣。 这里的问题是

const test1 = async () => {
    setTimeout(
        () => {
            return 5;
        },
        2000,
    )
}

test1 是一个异步函数,但 setTimeout 不是。

setTimeout 只会安排您传递的任何内容并立即返回其 timeoutID。 在这种情况下,您确实需要手动处理 Promise 代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2023-03-05
    • 2020-02-18
    • 1970-01-01
    相关资源
    最近更新 更多