Javascript 异步功能 - 等待不等待承诺

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45876514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:15:21  来源:igfitidea点击:

async function - await not waiting for promise

javascriptnode.jsasynchronousecmascript-2017

提问by hg_git

I'm trying to learn async-await. In this code -

我正在尝试学习异步等待。在这段代码中 -

const myFun = () => {
    let state = false;

    setTimeout(() => {state = true}, 2000);

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if(state) {
                resolve('State is true');
            } else {
                reject('State is false');
            }
        }, 3000);
    });
}

const getResult = async () => {
    return await myFun();
}

console.log(getResult());

why am I getting output as -

为什么我得到的输出是 -

Promise { <pending> }

Instead of some value? Shouldn't the getResult()function wait for myFun()function resolve it's promise value?

而不是一些价值?getResult()函数不应该等待myFun()函数解析它的承诺值吗?

采纳答案by Ben Fortune

If you're using async/await, all your calls have to use Promises or async/await. You can't just magically get an async result from a sync call.

如果您使用 async/await,则所有调用都必须使用 Promises 或 async/await。您不能只是神奇地从同步调用中获得异步结果。

Your final call needs to be:

您的最终通话需要是:

getResult().then(response => console.log(response));

Or something like:

或类似的东西:

(async () => console.log(await getResult()))()

回答by Pim_nr_47

What you need to understand is that async/await does not make your code run synchronously, but let's you write it as if it is:

您需要了解的是 async/await 不会使您的代码同步运行,但让我们将其编写为:

In short: The function with async in front of it is literally executed asynchronously, hence the keyword "async". And the "await" keyword wil make that line that uses it inside this async function wait for a promise during its execution. So although the line waits, the whole function is still run asynchronously, unless the caller of that function also 'awaits'...

简而言之:前面带有 async 的函数实际上是异步执行的,因此关键字“async”。并且“await”关键字将使在此异步函数中使用它的那行在执行期间等待承诺。因此,尽管线路等待,整个函数仍然异步运行,除非该函数的调用者也“等待”......

More elaborately explained: When you put async in front of a function, what is actually does is make it return a promise with whatever that function returns inside it. The function runs asynchronously and when the return statement is executed the promise resolves the returning value.

更详细的解释:当你把 async 放在一个函数前面时,实际上是让它返回一个承诺,无论该函数在其中返回什么。该函数异步运行,当执行 return 语句时,promise 会解析返回值。

Meaning, in your code:

意思是,在您的代码中:

const getResult = async () => {
    return await myFun();
}

The function "getResult()" will return a Promise which will resolve once it has finished executing. So the lines inside the getResult() function are run asynchronously, unless you tell the function calling getResult() to 'await' for it as well. Inside the getResult() function you may say it must await the result, which makes the execution of getResult() wait for it to resolve the promise, but the caller of getResult() will not wait unless you also tell the caller to 'await'.

函数“getResult()”将返回一个 Promise ,一旦它完成执行就会解决。因此 getResult() 函数内的行是异步运行的,除非您也告诉调用 getResult() 的函数“等待”它。在 getResult() 函数中,您可能会说它必须等待结果,这使得 getResult() 的执行等待它解决承诺,但是 getResult() 的调用者不会等待,除非您也告诉调用者“等待” '。

So a solution would be calling either:

所以一个解决方案将调用:

getResult().then(result=>{console.log(result)})

Or when using in another function you can simply use 'await' again

或者在另一个函数中使用时,您可以再次使用“await”

async callingFunction(){
    console.log(await(getResult());
}

回答by ekerner

There is no point to async and await when this is the actual case:

在实际情况下,异步和等待没有意义:

Promise.resolve(3).then(console.log); console.log(4);
4
3

In other words, since the then() forks and runs slower than the subsequent statements (even for a resolved Promise) then we need to put the subsequent statements inside the then, like:

换句话说,由于 then() fork 和运行比后续语句慢(即使对于已解决的 Promise),那么我们需要将后续语句放在 then 中,例如:

Promise.resolve(3).then(_ => { console.log(_); console.log(4); });
3
4

And since that is true then why bother to await. So Im yet to see why async and await even exist.

既然这是真的,那为什么还要等待。所以我还没有看到为什么 async 和 await 存在。

回答by Nassim

This is my routine dealing with awaitand asyncusing a Promisewith resolveand rejectmechanism

这是我使用具有解析拒绝机制的Promise处理等待异步的例行程序

    // step 1 create a promise inside a function
    function longwork()
    {
        p =  new Promise(function (resolve, reject) {
            result = 1111111111111 // long work here ; 

            if(result == "good"){
                resolve(result);
            }
            else
            {
                reject("error ...etc")
            } 
        })

        return p
    }

    // step 2 call that function inside an async function (I call it main)and use await before it
    async function main()
    {
         final_result = await longwork();
         //..

    }  

    //step 3 call the async function that calls the long work function
    main().catch((error)=>{console.log(error);})

Hope that saves someone valuable hours

希望可以节省某人宝贵的时间