当我在函数外使用它时,promise 的返回值是不同的,我无法真正理解为什么

Returning value of promise is diffrent when I use it outside function and cant really get why

我有2个js文件。我正在尝试调用 listings.js 中函数 all() 的承诺结果 index.js。如果我在 async function all() 中 console.log,它会记录带有数据的预期对象,一切都很好但是一旦我尝试将 return 值设置为 index.js 并将其存储在变量中,然后console 这个变量,它显示在它里面有一些状态 panding 的承诺......什么?有什么我不知道的吗? 我再次将它包装到 await 中以获得结果,这正是我在该函数中所期望的,但是一旦我从 func 中获得 return 值,它就会失去承诺。 问题:如何正确 return 值到变量?

index.js

import 'babel-polyfill';
import {all} from './listings';

let result = all();
console.log(result); //returns promise, why???

listings.js

export async function all() {
    let res = await makeRequest('http://sellbuyschool42.com/listings');
    console.log(res); //return expected object with data, all is GOOD
    return res;
}

function makeRequest($url, options= {})
{
    return fetch($url).then((responce) => {
        if(responce.status != 200)
        {
            return responce.text().then((text) => {
                throw new Error(text);
            })
        }
        return responce.json();
    })
}

请记住,异步函数return是一个承诺。它不是 return 该承诺的结果。相反,您必须解决该承诺才能获得价值。

在您的 index.js 文件中,当您调用 all() 函数时,您需要使用 then()await 来获取异步函数的实际结果。

let result = await all();
console.log(result);

all().then((result) => {
    console.log(result);
}

请记住,在第一个解决方案中(如果您使用 await),您还需要使该父函数异步。