提问者:小点点

返回即时响应,无需等待异步函数


我正在编写一个API,它接收一个请求&; 然后在Puppeteer上运行一个相当复杂的函数,但是我不希望API在抛出成功响应之前等待函数执行完毕,因为它只是一个提交API?

以下是当前的流程:

const createOrder = async (req, res) => {
    try {

        console.log(req.body);

        let params = await parser.parseStringPromise(req.body.parameters);

        device_imei = params.PARAMETERS.IMEI;

        //config
        axios.defaults.withCredentials = true;
        axios.defaults.timeout = 15000;
        userProfile = faker.entity.user();

        recaptcha_solution = await get_captcha_solution();

        page = await browser.newPage();

        page.on('response', handle_response);

        await page.goto('https://www.website.com', {
            waitUntil: 'networkidle0',
        });

        //etc......

    } catch (error) {

        if(page) {
            await page.close();
        }

        return res.send(error_response(error.message));

    }
});

app.post('/api/index.php', async function (req, res) {
    switch(req.body.action) {
        case "placeimeiorder":
            return await createOrder(req, res);
        default:
            return res.send(error_response('Invalid Action'));
    }
});

我怎么能让它只执行函数&; 然后在脚本在后台运行时立即返回JSON响应?


共1个答案

匿名用户

async函数中,await在允许函数逻辑继续之前等待承诺解决。 如果你不想等待一个承诺的解决,就不要对它使用await

因此,例如,如果您想要启动而不是等待的操作是page.goto调用,则删除它前面的await。 您还可以通过.catch添加拒绝处理程序,以便处理和报告它返回的任何错误(异步地,在函数返回后):

//  v−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− no `await`
    page.goto('https://www.website.com', {
        waitUntil: 'networkidle0',
    })
    .catch(error => {
        // Handle/report the fact an error occurred; at this point, your
        // `createOrder` call has already finished and sent the response, so
        // you can't send an error response but you can use the information
        // in some other way
    });

相关问题