【问题标题】:Variables Not Being Retained未保留的变量
【发布时间】:2017-11-04 09:56:50
【问题描述】:

好的。

我的问题在于 Javascript 对象 itemListpriceList - 它们没有正确保留在 .then() 部分中。

这是我遇到问题的部分:

var stmt = `SELECT * FROM SRV${msg.guild.id}`;
var itemList = {};
var priceList = {};
var num = -1;
sql.each(stmt, function(err, row) {
    num++
    if(row.items!="ITEMS") { itemList[num] = row.items; }
    if(row.prices!="PRICES") { priceList[num] = row.prices; }
    console.log("---------\n" + JSON.stringify(itemList, null, 4) + "\n" + JSON.stringify(priceList, null, 4));
})
.then((itemList, priceList) => {
    console.log("----E----\n" + JSON.stringify(itemList, null, 4) + "\n" + JSON.stringify(priceList, null, 4) + "\n----E----");
    let cmd = require("./itemsPROCESS.js");
    cmd.run(transfer, msg, args, itemList, priceList);
});

这是它输出的重要部分:

我尝试过使用字符串而不是 Javascript 对象,但它似乎也不喜欢那样,并且输出相同。

5undefined 部分应该类似于它上面的位,但事实并非如此。

可能与null 部分有关吗?如果是这样,这是否意味着它不适用于true - false - undefined 等?

【问题讨论】:

    标签: javascript node.js object


    【解决方案1】:

    删除参数itemListpriceList,你的代码应该没问题。

    您在.then 函数中引用的itemList 实际上是由SQL 承诺解决的。

    .then(() => {...});
    

    【讨论】:

    • 哎哟。我对 ES6 的东西还很陌生,因为我通常不在 Node.JS 中工作。你能告诉我为什么它输出的是什么吗?在函数中使用itemListpriceList 时是否不小心将随机值分配给它?
    • 当然.... .then 函数通常从 Promise 获取解析值作为其第一个参数。我从来没有在那里看到过第二个论点。如果您希望将某些值从您的async 函数传递到.then 内部的函数,这很有用。在您的情况下, sql.each 返回一个承诺,该承诺在解决时返回值 5.. 类似于 promise.resolve(5)。这作为 then .then 函数的参数出现,您可以打印值 5
    • 谢谢!接受你的回答。
    • @PlutonusCommissions 很高兴能为您提供帮助。 :)
    【解决方案2】:

    您正在使用全局范围的itemListpriceList,因此不要在then 的本地范围内重新定义它们。只需从 then 中删除这些参数

    .then(() => {
        console.log("----E----\n" + JSON.stringify(itemList, null, 4) + "\n" + JSON.stringify(priceList, null, 4) + "\n----E----");
        let cmd = require("./itemsPROCESS.js");
        cmd.run(transfer, msg, args, itemList, priceList);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      相关资源
      最近更新 更多