首页 > 解决方案 > JS - then 与 async / await 返回值

问题描述

我试图将我的“问题”简化为更简洁。我正在尝试从异步函数中返回(获取必须在特定函数中,因为我正在那里进行其他调用)。

单击按钮时会触发 testAsync :

async function testAsync(){
    console.log("start async");
    let result = await go(); // Waiting promise
    console.log("result "+result);
    alert(result);
}

然后我想做“去”的事情

async function go(){
    fetch('https://apiurl.com', {
        method: 'POST',
        body: '{"URL":"anotherurltotest.com"}'
    })
    .then(response => response.json())
    .then(json => {return json;})
    .catch(err => {
        console.log(err)
    })
}

使用此方法:结果未定义并立即触发,而不是等待 then/fetch 的返回 json。

但我试过这个:

async function go(){
    return await fetch('https://apiurl.com', {
        method: 'POST',
        body: '{"URL":"anotherurltotest.com"}'
    })
    .then(response => response.json())
    .catch(err => {
        console.log(err)
    })
}

这样,结果仅在短时间内被触发并被填充。

为什么当时的回报不起作用?但回来等待所有的取货,是吗?

谢谢 :)

标签: javascriptasync-awaitfetch

解决方案


推荐阅读