Node.js中的同步请求 [英] Synchronous Requests in Node.js

查看:62
本文介绍了Node.js中的同步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使Node.js中的请求"模块以同步方式加载内容?我见过的最好的建议是以某种方式使用回调来使函数在完成之前不返回自身.我正在尝试在代码中内联使用'request'函数(需要根据无法放置在回调中的数据来处理事情).

How could I make the 'request' module in Node.js load things in a synchronous fashion? The best advice I've seen is to somehow use the callback to get the function to not return itself until it is done. I am trying to use the 'request' function inline in code (things need to be processed based on that data that can't be placed in callbacks).

那么我如何使用'request'模块的回调来阻止它返回自身,直到完成加载资源为止?

So how could I use the callback of the 'request' module to keep it from returning itself until it is finished with loading the resource?

我正在做的是运行一个循环,该循环从API下载两个值,然后必须根据这些值进行一些数学运算.虽然可以在回调函数中完成数学运算,但循环将继续进行,而无需执行下一个操作所需的值.(因此,停止循环前进直到数据准备就绪将解决此问题)

What I'm doing is running a loop that downloads two values from an API, and then has to do some math based on those values. While the math could be done in callbacks... the loop would advance without the values it needs to perform the next operation. (So stopping the loop from advancing until the data is ready would solve the issue)

    /* loop */ {
         /* URL Generation */


    request( {url: base + u_ext}, function( err, res, body ) {
        var split1 = body.split("\n");
        var split2 = split1[1].split(", ");
        ucomp = split2[1];
    });

    request( {url: base + v_ext}, function( err, res, body ) {
        var split1 = body.split("\n");
        var split2 = split1[1].split(", ");
        vcomp = split2[1];
    });

    /* math which needs to be after functions get variables and before loop advances */
    }

推荐答案

在2018年,您可以使用Node.js中的 async await 编写常规"样式

In 2018, you can program the "usual" style using async and await in Node.js.

下面是一个示例,该示例将请求回调包装在Promise中,然后使用 await 来获取已解析的值.

Below is an example, that wraps request callback in a promise and then uses await to get the resolved value.

const request = require('request');

// wrap a request in an promise
function downloadPage(url) {
    return new Promise((resolve, reject) => {
        request(url, (error, response, body) => {
            if (error) reject(error);
            if (response.statusCode != 200) {
                reject('Invalid status code <' + response.statusCode + '>');
            }
            resolve(body);
        });
    });
}

// now to program the "usual" way
// all you need to do is use async functions and await
// for functions returning promises
async function myBackEndLogic() {
    try {
        const html = await downloadPage('https://microsoft.com')
        console.log('SHOULD WORK:');
        console.log(html);

        // try downloading an invalid url
        await downloadPage('http://      .com')
    } catch (error) {
        console.error('ERROR:');
        console.error(error);
    }
}

// run your async function
myBackEndLogic();

这篇关于Node.js中的同步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆