簡體   English   中英

Node.js - Javascript - 返回異步變量

[英]Node.js - Javascript - Returning Async Variables

我正在開發一個不和諧機器人,它將從我創建的 Google 電子表格中獲取隨機值。 我已經編寫了我的 accessSpreadsheet.js 文件,以便它可以從 Google Sheets 中獲取數據,這是異步完成的。 我可以通過 console.log 從異步函數中注銷我想要的數據,但是我不能通過返回異步數據來設置其他變量,而是返回 undefined。

首先,我有一個 discord.js,它接受來自 Discord 的輸入並調用我的 giRandom 函數並用輸出回復用戶。

if(input === "!0"){
    var output = giRandom("1"); //this seed just guarantees a "true" outcome for  testing the boolSet function (located below)
    msg.reply(output); //Output's the returned giRandom data (currently replies but output is null)
}

Discord 正在從 giRandom.js 調用以下函數 在我們到達var output = builder(seed_data);之前,一切似乎都在這里工作var output = builder(seed_data);

//Returns a random number when fed a seed
function giRandom(seed) {

    //Seperate random seed js file. Working properly.
    var seedrandom = require('seedrandom');
    var rng = seedrandom(seed);

    var seed_Data = seedData(rng()); //Function below
    var output = builder(seed_Data); //Function below //Returning Undefined

    return output; //Returns output to discord.js (msg.reply(output))
}

exports.giRandom = giRandom; //located at end of file, not in a function

我的 giRandom 函數正在調用 seedData 和 builder 函數(都位於 giRandom.js 中)

種子數據函數

//Takes the seed generated by seedrandom (something like 0.1189181568115987) and seperates each digit into an array, ignoring NaN digits (in this case the decimal point)
function seedData(data){
    var counter = 0; //used to determine amount of NaN digits

    //Counts each NaN in inputArray
    var inputArray = Array.from(data.toString()).map(Number);
    for (var i = 0; i < inputArray.length; i++) {
        if (inputArray[i] >= 0) { //Checks for NaN
            if (debug) {
                console.log("inputArray[" + i + "] | " + inputArray[i]);
            }
        } else { //If NaN counter++
            counter++;
        }
    }

    var outputArray = new Array(counter); //Creates output array with correct size for all NaN values
    counter = 0; //Reset counter to 0

    //Creates outputArray containing all seed digits
    for (var i = 0; i < inputArray.length; i++) {
        if (inputArray[i] >= 0) {
            outputArray[counter] = inputArray[i];
            counter++;
        }
    }

    //Debug function to view output values
    for (var i = 0; i < outputArray.length; i++) {
        if (debug) {
            console.log("outputArray[" + i + "] | " + outputArray[i]);
        }
    }

    return outputArray; //returns outputArray to seed_Data in giRandom function
}

建造者功能

//Takes seed_Data from giRandom function and determines the value's output
function builder(data) {

    //Booleans, determine if each category returns a value based on boolSet() (function below)
    var raceBool;

    //data[0] is always a value of 0. 16 Total Usable values 1-17
    raceBool = boolSet(data[1]);


    if (raceBool == true) {
        var raceData = sheetToArray(1);
        console.log("raceData | " + raceData);
        return raceData; //Returning undefined
    }
}

我的構建器函數正在調用 boolSet 和 sheetToArray 函數(均位於 giRandom.js 中)

boolSet 函數

//Each seed digit can be 0-9. If the digit passed (boolData) matches the value for valueTrue, valueFalse, or valuePick the output will be set accordingly. (Currently will always output True)
function boolSet(boolData) {
    var valueTrue = [0, 1, 2, 3];
    var valueFalse = [4, 5, 6, 7];
    var valuePick = [8, 9];

    //Loop through valueTrue and compare with boolData
    for (var i = 0; i <= valueTrue.length; i++) {
        if (boolData == valueTrue[i]) {
            if (debug) {
                console.log("boolData | " + boolData + " | true");
            }
            return true;
        }
    }

    //Loop through valueFalse and compare with boolData
    for (var i = 0; i <= valueFalse.length; i++) {
        if (boolData == valueFalse[i]) {
            if (debug) {
                console.log("boolData | " + boolData + " | false");
            }
            return false;
        }
    }
    //If !true && !false, must be "pick". This value will allow the end user to choose their data (in this case race)
    return "pick";
}

sheetToArray 函數

//takes an int for sheetNum that determines which sheet in the project to load 
function sheetToArray(sheetNum){
    var sheetArray = []; //Array that holds all rows of a particular worksheet, used to build spreadsheetArray
    var cellArray = []; //Array that holds all cells in a particular row of the worksheet used to build sheetArray
    var rowArrayCount = 1; //Counter to determine rows in cells forEach loop

    /*I believe this is where my problem probably lies*/
    //Calling async function accessSpreadsheet from spreadsheet.js
    accessSpreadsheet(sheetNum).then(function (arr) {
        var cells = arr;
        //loop through all cells in current sheet
        cells.forEach(cell => {
            if (cell.row > rowArrayCount) { //True determines that data is now on the next row of current sheet
                rowArrayCount++;
                sheetArray.push(cellArray); //push last row to sheetArray
                cellArray = []; //reset cellArray for new row
            }
            cellArray.push(cell._value); //push final row to cellArray
        })//Exit forEach
        sheetArray.push(cellArray); //push all rows to sheetArray
        var raceLength = sheetArray.length; //Returns value correctly
        console.log("raceLength | " + raceLength); //Returns value correctly
        console.log("sheetArray | " + sheetArray); //Returns value correctly
        return sheetArray; //Returns undefined
    })
}

要訪問 Google 表格,我有一個單獨的 js 文件。 這是異步函數 accessSpreadsheet() 所在的位置

accessSpreadsheet.js

//Google Sheet Access Const
const GoogleSpreadsheet = require('google-spreadsheet');
const { promisify } = require('util');
const creds = require('./client_secret.json');
const doc = new GoogleSpreadsheet('**************'); //Google sheet we have access to (removed for security)

module.exports = accessSpreadsheet = async (sheetNum) => {
    await promisify(doc.useServiceAccountAuth)(creds);
    const info = await promisify(doc.getInfo)();
    const sheet = info.worksheets[sheetNum];

    //Async get sheet's cells without an offset
    const cells = await promisify(sheet.getCells)({
        offset: 0
    })

    return cells;
}

javascript 承諾的基礎知識:

accessSpreadsheet 定義類似於

async accessSpreadsheet(args...){
   //Do stuff
   return something;
}

或喜歡:

accessSpreadsheet(args...){
   return Promise(function (resolve,reject){
       // Do stuff
       resolve(return_value)
   })
}

由於 javascript 是事件驅動的,您不能讓它等待 i/o,因為它不利於用戶體驗。

因此,您可以通過使所有代碼異步並使用 await 關鍵字等待 accessSpreadsheet 來解決您的問題。

像這樣 :

await accessSpreadsheet()

這將在進入下一行之前等待 accessSpreadsheet 返回。

這是一個帶有 promise 的基本競爭條件場景。

您應該刪除無效的承諾:

const info = await promisify(doc.getInfo)();

可以寫成:

const info = doc.getInfo();

並記錄錯誤:

accessSpreadsheet(sheetNum).then(function (arr) {
   // somecode 
}).catch(console.error)

這可能會讓你的生活更輕松

暫無
暫無

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

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