Node.js 中的竞争条件

Race condition in Node.js

我正在学习 Node.js 并为 API 练习。我想从 twitch 获取有关游戏前 200 个流的数据。但是,由于限制是 100,所以我必须在 for 循环中执行两次请求。问题是竞争条件。当我请求 0-100 和 100-200 的数据时,我不知道哪个数据先到。因此,我标记记录状态以记录哪个先出现,但它似乎无法正常工作。谁能指导我我的方法有什么问题?如何改进?谢谢!

const request = require('request');
const process = require('process');

const args = process.argv[2];
let offset = 0;
let flag = false;
const clientID = 'agdn5682y521syqhwkdrqmw7ho6v7d';

function getGameInfo(gamename, pagination, clientid, tag) {
  request(
    {
      method: 'GET',
      url: `https://api.twitch.tv/kraken/streams/?game=${gamename}&limit=100&offset=${pagination}`,
      headers: {
        'Client-ID': clientid,
        'Accept': 'application / vnd.twitchtv.v5 + json'
      }
    },
    (err, res, body) => {
      if (!tag) {
        tag = true;
        if (err) {
          return console.log('Error', err)
        };
        const data = JSON.parse(body);

        const result = data.streams;

        if (data.status === 404) {
          console.log('fail to get data!');
        };
        for (let j = 0; j < result.length; j++) {
          console.log(result[j].channel._id, result[j].channel.display_name);
        };
        tag = false;
      }
    }
  )
}

for (let i = 0; i < 2; i++) {
  getGameInfo(args, offset, clientID);
  offset += 100;
}

这是一个你可以做的小例子。 Promise 等到它得到 resolve()

然后就可以调用下一个offset了。

const request = require('request');
const process = require('process');

const args = process.argv[2];
let offset = 0;
let flag = false;
const clientID = 'agdn5682y521syqhwkdrqmw7ho6v7d';



function getGameInfo(args, offset, clientID){
    return new Promise(function(resolve, reject){
      const options = {
      method: 'GET',
      url: `https://api.twitch.tv/kraken/streams/?game=${args}&limit=100&offset=${offset}`,
      headers: {
        'Client-ID': clientID,
        'Accept': 'application / vnd.twitchtv.v5 + json'
      }
    }
        request(options, function (err, response, body) {
            if (err) return reject(err);
            try {
                resolve(JSON.parse(body));
            } catch(e) {
                reject(e);
            }
        });
    });
}

getGameInfo("pubg", offset, clientID).then(function(val) {
    console.log(val);
}).catch(function(err) {
    console.log(err);
});