首页 > 解决方案 > 像使用 setTimeout 的承诺一样使用 setTimeout 构建异步不起作用

问题描述

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

标签: javascriptasynchronousasync-awaitpromise

解决方案


它未定义,因为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,
    )
}

推荐阅读