本文介绍了异步/等待返回Promise {< pending> }的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:尽管我使用了异步/等待,但为什么此日志承诺{未决}"呢?我检查了类似的问题和答案,似乎应该可以,但事实并非如此.我如何更改它以获得结果,为什么?谢谢.

my question is: why does this log 'promise {pending}' despite of i used async/await? I checked similar questions and answers on them and it seems like it should be okay but it is not. How do i change it to get the result and why? Thank you.

const rp = require('request-promise-native');

async function sampleFunc() {
    let sample = await rp({
        uri: 'http://google.com',
        jar: true
    });
    return sample;
}

async function f() {
    return await sampleFunc();
}

console.log( f());

推荐答案

async-await实际上只是诺言的语法糖,它不会使异步代码同步运行(即,它不会阻止代码执行).您的代码等效于以下内容:

async-await is really just syntactic sugar for promises, it doesn't make asynchronous code run synchronously (i.e. it doesn't block code execution). Your code is equivalent to the following:

function sampleFunc() {
    return new Promise(function(resolve) {
        rp({
            uri: 'http://google.com',
            jar: true
        }).then(function(sample) {
           resolve(sample);
        });
    });
}

function f() {
    return new Promise(function(resolve) {
        sampleFunc().then(function(result) {
            resolve(result);
        });
    });
}

console.log( f());

(是的,我知道上面的代码演示了一种反模式.这只是出于说明目的)

如您所见,async函数的真正作用是隐式返回一个承诺,该承诺将通过您最终返回在函数内部返回的值进行解析(如果您throw ). 这就是为什么async-await仅可用于功能,因此不适用于顶层的原因.

As you can see, what an async function really does is to implicitly return a promise that gets resolved with the value you eventually return inside the function (or rejected if you throw something). This is why async-await can only be used on functions and thus isn't applicable on the top level.

调用该函数的上下文完全不知道该函数是async的事实,它只是调用该函数,得到一个承诺并返回到下一行代码.您的console.log()居住在这种外部环境中,只能看到返回的承诺.

The context that called the function is entirely agnostic to the fact that the function is async, it just calls the function, gets a promise back and moves on to the next line of code. Your console.log() lives in this outside context and only sees the promise that was returned.

这篇关于异步/等待返回Promise {< pending> }的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:07