繁体   English   中英

第二个异步功能永远不会完成

[英]Second async function never finishes

这是我为电子应用编写的一些代码的简化版本。 我需要两个函数来运行,一个接一个。 每个人都需要进行API调用,然后等待响应完成。

async function build_page()
{
    await func_1()
    await func_2()
}

async function func_1()
{
    console.log("1 Start")

    await send().then(
        function (response)
        {
            console.log("1 Middle")
        }
    )
    console.log("1 End")
}

async function func_2()
{
    console.log("2 Start")

    await send().then(
        function (response)
        {
            console.log("2 Middle")
        }
    )
    console.log("2 End")
}

function send()
{

    const request = require("request-promise-native")

    return request({
        url: "http://localhost:7296/Categories",
        method: "POST",
        json: true,
        body: {"token": localStorage.getItem("token")}
    })

}

我希望控制台打印“ 1开始,1中间,1结束,2开始,2中间,2结束”,但是目前,它只能显示为“ 2开始”。 我不确定func_2为何未完成。 当我注释掉对func_1的调用时,func_2按预期完成,并且当我将调用交换到func_1和func_2时,func_1仅使其变为“ 1 Start”。

问题一定是与请求承诺本机库有关,因为我能够通过移植使用提取库来解决此问题。

我用以下代码替换了send函数的主体:

return fetch(
    "http://localhost:7296/".concat(endpoint),
    {
        method: method,
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(input)
    }
).then(response => response.json())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM