簡體   English   中英

嵌套Javascript異步函數

[英]Nested Javascript async functions

我正在編寫《爐石傳說》開箱模擬器。 嘗試打開多個包裝時遇到問題。 當我打開1包時,我得到了5張卡片的陣列。 當我打開2包時,我得到2張10張卡片的陣列。 我希望它是1張10張卡片的陣列。 我在想這與異步函數或回調有關,但不確定如何解決。

var dataPromise;
var allCards;
var set;
var numberOfPacks;
var commons;
var rares;
var epics;
var legendarys;
var card;
var cardRob;
var pack = [];
var collection = [];
var pittyE;
var pittyL;
$(document).ready(function(){
    getCardData()
    .done(function(data){
        allCards = data;    
    });
    $('#submit').click(function(event){
        event.preventDefault();
            filterByQuality();
            openPacks();
            console.log(collection);
        });
});
function getCardData() {
  if(!dataPromise){
    dataPromise = $.ajax({ // Store jQuery promise so that we can return it for subsequent calls ensuring only one AJAX request is made
      url: 'https://omgvamp-hearthstone-v1.p.mashape.com/cards?collectible=1',
      type: 'GET',
      dataType: 'json',
      beforeSend: function(xhr) {
        xhr.setRequestHeader("X-Mashape-Authorization", "mXtnPm3ltOmshc9dQJjtVdKzfnhbp14UZncjsnfzwvp6uLiMwH");
      }
    });
  } 
  return dataPromise;
};
function filterByQuality(){
     set = document.getElementById('sets').value;
     commons = allCards[set].filter(function(common){
        return common.rarity == "Common"});
     rares = allCards[set].filter(function(rare){
        return rare.rarity == "Rare"});
     epics = allCards[set].filter(function(epic){
        return epic.rarity == "Epic"});
     legendarys = allCards[set].filter(function(legendary){
        return legendary.rarity == "Legendary"});

};
function getCard(){
    var x  = Math.floor((Math.random() * 10000) + 1);
    if (x <= 96){
        card = legendarys[Math.floor(Math.random() * (legendarys.length))];
        pittyL = 0;
    }else if (x > 96 && x <= 420){
        card = epics[Math.floor(Math.random() * (epics.length))];
        pittyE = 0;
    }else if (x > 420 && x <= 2167){
        card = rares[Math.floor(Math.random() * (rares.length))];
    }else{
        card = commons[Math.floor(Math.random() * (commons.length))];
    }
    pack.push(card);
};
function getCardRob(){
    var x = Math.floor((Math.random() * 10000) + 1);
    if (x <= 96){
        card = legendarys[Math.floor(Math.random() * (legendarys.length))];
        pittyL = 0;
    }else if (x > 96 && x <= 420){
        card = epics[Math.floor(Math.random() * (epics.length))];
        pittyE = 0;
    }else{
        card = rares[Math.floor(Math.random() * (rares.length))];
    }
    pack.push(card);
};
function getLegendary(){
    card = legendarys[Math.floor(Math.random() * (legendarys.length))];
    pack.push(card);
    pittyL = 0;
};
function getEpic(){
    card = epics[Math.floor(Math.random() * (epics.length))];
    pack.push(card);
    pittyE = 0;
};
function getPack(){
    pittyL ++;
    pittyE ++;
    if (pittyL == 40 && pittyE == 10){
        getLegendary();
        getEpic();
        getCard();
        getCard();
        getCard();
    } else if (pittyL = 40 && pittyE < 10){
        getLegendary();
        getCard();
        getCard();
        getCard();
        getCard();
    } else if (pittyL < 40 && pittyE == 10){
        getEpic();
        getCard();
        getCard();
        getCard();
        getCard();
    } else {
        getCardRob();
        getCard();
        getCard();
        getCard();
        getCard();
    }
    collection.push(pack);
};
function openPacks(){

    numberOfPacks = document.getElementById('nop').value;

    for (var i = 0; i < numberOfPacks; i++){
        getPack();
    }

};

這是HTML

​<html>
    <body>
        <header>
            <h1>Hearthstone Pack Simulator</h1>
                <form>
                <select name="sets" id="sets">
                    <option value="Classic">Classic</option>
                    <option value="Goblins vs Gnomes">Goblins vs Gnomes</option>
                    <option value="Journey to Un'Goro">Journey to Un'Goro</option>
                    <option value="Mean Streets of Gadgetzan">Mean Streets of Gadgetzan</option>
                        <option value="The Grand Tournament">The Grand Tournament</option>
                        <option value="Whispers of the Old Gods">Whispers of the Old Gods</option>
                </select>
                    <select name="no of packs" id="nop">
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="20">20</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                    </select>
                <input type="submit" id="submit">
                </form>
        </header>
        <div>
        </div>
    </body>
</html>

1)您在if (pittyL = 40 ,應該是if (pittyL == 40)上有錯字。

2)我建議您使用一種方法來獲取所需的卡數,以便可以執行getCard(3); 獲得3張卡,避免多次調用相同的功能。

3)至於包裝問題,您的包裝變量始終是相同的,並且始終將卡推入該變量,因此,如果您打開100個包裝,則包裝將有500張卡。 至於為什么有2個裝,那是因為您在做collection.push(pack); 每次打開包裝時,因此您每次都在努力收集相同的包裝參考。

當您調用getCard() (或其任何版本)時,您正在更新global pack 您最終要兩次為兩個包調用getCard() 10次​​,因此同一全局pack將被更新為總共10張卡。 collection也是全球性的,並且兩次使用同一pack進行更新。

為了使其正常工作,您應該在每次調用getPack()時創建一個新的pack對象。

一般來說,請勿使用全局變量來管理此狀態。 相反,每次調用getPack()getCollection()等等時,都創建一個包或集合對象,然后將其返回。

您只有一個異步功能,可以從一開始就獲取所有卡數據。 異步性不會給您帶來任何問題。

function getCard() {
  let card = /* snip */
  return card;
}
function getPack() {
  let pack = [];
  pack.push(getCard());
  /* snip -- add more cards */
  return pack;
}

每個getPack()調用都需要單獨的包數組。

請,為您的榮幸將其重寫為對象,也請考慮范圍

一旦使用了對象和正確的作用域,就應該沒事了。

var variable_passed_to_function;
variable_passed_to_function = 'foo';

console.log( variable_from_outside_of_function );

function myFunction( variable_from_outside_of_function ) {
    let variable_for_only_inside_of_function;
    variable_for_only_inside_of_function = 'bar';
    console.log( variable_from_outside_of_function );
    console.log( variable_for_only_inside_of_function );
    variable_from_outside_of_function = 'baz';
    console.log( variable_from_outside_of_function );
    console.log( variable_for_only_inside_of_function );
    return 'this can be also usable';
}

another_variable = myFunction( variable_passed_to_function );

console.log( another_variable );
console.log( variable_passed_to_function );
console.log( variable_for_only_inside_of_function );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM