te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>Javascript - Async await and fetch - return the value, not the promise? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - Async await and fetch - return the value, not the promise? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to work with async await and fetching data using the fetch api

My problem is, I just don't quite understand how I really get the answer from the server and not the status of the promise. I get the following in the console

Promise {<pending>}
-------------------------------
{locale: "en"}

but what I rather expect is the server response which should be "locale: en".

my code:

const locale = getLocale();
console.log(locale) // here I want to have "locale: en" as a output


async function fetchLocale() {
    return await fetch('/get-language', {
        headers: {
            'Accept': 'application/json'
        },
        method: 'GET',
    }).then(response => {
        if (response.ok) {
            return response.json()
        }
        return Promise.reject(Error('error'))
    }).catch(error => {
        return Promise.reject(Error(error.message))
    })
}

async function getLocale() {
    return await fetchLocale();
}

The goal I want to archive is, to return this "locale: en" response and store it in the "locale" const at the beginning of my code example.

KR

I'm trying to work with async await and fetching data using the fetch api

My problem is, I just don't quite understand how I really get the answer from the server and not the status of the promise. I get the following in the console

Promise {<pending>}
-------------------------------
{locale: "en"}

but what I rather expect is the server response which should be "locale: en".

my code:

const locale = getLocale();
console.log(locale) // here I want to have "locale: en" as a output


async function fetchLocale() {
    return await fetch('/get-language', {
        headers: {
            'Accept': 'application/json'
        },
        method: 'GET',
    }).then(response => {
        if (response.ok) {
            return response.json()
        }
        return Promise.reject(Error('error'))
    }).catch(error => {
        return Promise.reject(Error(error.message))
    })
}

async function getLocale() {
    return await fetchLocale();
}

The goal I want to archive is, to return this "locale: en" response and store it in the "locale" const at the beginning of my code example.

KR

Share Improve this question edited Jan 3, 2020 at 17:43 JuniorDev asked Jan 3, 2020 at 17:25 JuniorDevJuniorDev 1621 gold badge3 silver badges15 bronze badges 10
  • Oh - and I'm using plain JS – JuniorDev Commented Jan 3, 2020 at 17:26
  • 1 your getLocale() function does not return anything. – Pointy Commented Jan 3, 2020 at 17:27
  • 1 Replace console.log(response) with return response, and fetchLocale() with getLocale() – user5734311 Commented Jan 3, 2020 at 17:29
  • 1 ... and then understand that what you're getting back is a Promise, so you still won't directly get the locale. You'll need to add a .then() callback or else wrap the call in another immediately invoked async function wrapper. – Pointy Commented Jan 3, 2020 at 17:32
  • 1 @JuniorDev please see my or TKoL's answers. You cannot bring async results into synchronous context like the top level of your file, it just isn't possible. You need to consume the function with either .then() or await in an async function. – Klaycon Commented Jan 3, 2020 at 17:44
 |  Show 5 more ments

2 Answers 2

Reset to default 10

Your function should look more like this:

async function getLocale() {
    let response = await fetch('/get-language', {
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        method: 'GET',
    });
    // you can check for response.ok here, and literally just throw an error if you want
    return await response.json();
}

And you can consume the result of that in an async function using await

const locale = await getLocale();
console.log(locale);

or by using the promise methods

getLocale().then(function(locale){
    console.log(locale);
})

To get the value a Promise resolves with and not the promise itself, use .then() or await. Note that both require a callback or asynchronous context as it's simply not possible to bring this asynchronous result to a synchronous context such as the top level of your file.

getLocale().then(locale => {
    console.log(locale);
    //locale is only valid here
});
发布评论

评论列表(0)

  1. 暂无评论