0

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();

如果我使用awaittest2可以工作,但它不能工作test1。这是为什么 ?async/await仅用于处理未使用的承诺,.then或者我可以使用asyncwith而不是return result使用Promisewith resolve

4

2 回答 2

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,
    )
}
于 2021-11-08T20:51:43.857 回答
1

这是一个有趣的。这里的问题是

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

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

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

于 2021-11-08T20:52:39.900 回答