NodeJS在循环中使用请求

时间:2017-11-03 12:58:31

标签: node.js

我使用NodeJS并请求lib向API发出一些请求。

我现在明白所有请求都是异步的,所以它不会“等待”GET调用的结果,所以我的Loop索引总是一样的。

我想知道是否有任何简单的方法(没有任何lib)等待请求调用的响应?

目前,我的代码是:

for (var i in entries) {    
    var entryId = entries[i]['id'];

    var options = {
        url: 'https://api.com/'+ entryId +'/get/status',
        method: 'GET',
        headers: {
            'Authorization': auth
        }
    };

    console.log(' ENTRY ID > '+ entryId);

    request(options, function(error, response, body) {          
        var response = JSON.parse(body);

        if (response.status.code == 200) {

            var id = response.status.id;
            var data = [];
            data['id'] = id;

            data = JSON.stringify(data);

            // show first entryId of loop  
            console.log(' > MY ID : '+ id + ' - '+ entryId);

            options = {
                host: hostname,
                port: 80,
                path: '/path/function2',
                method: 'PUT'
            };

            var post = http.request(options, function(json) { 
                var body = '';

                json.on('data', function(d) {
                    body += d;
                });
                json.on('end', function() {
                    console.log('> DONE');
                });

            }).on('error', function(e) {
                console.log(e);
            });

            post.write(data);
            post.end(); 
        }
    }); 
}

2 个答案:

答案 0 :(得分:0)

您正在寻找async / await。

将您的逻辑包含在异步函数中,然后您可以等待承诺。

const request = require('request-promise')
async function foo (a) {
   for (i in a)
      try {
         let a = await request('localhost:8080/')
         // a contains your response data.
      } catch (e) {
         console.error(e)
      }  
}
foo([/*data*/])

只需使用请求模块的承诺版本。

答案 1 :(得分:0)

您还可以使用Promises等待异步代码完成。

function asyncCode(msg, cb){
  setTimeout(function() {cb(msg);}, 1000);
}

var p1 = new Promises(function(resolve){
    asyncCode("my asyncCode is running", resolve);
});

p1.then(function(msg) {
    console.log(msg);
}).then(function() {
    console.log("Hey I'm next");
});

console.log("SyncCode, Async code are waiting until I'm finished");