未在 Promise 的 .then() 部分内设置变量[重复]

Posted

技术标签:

【中文标题】未在 Promise 的 .then() 部分内设置变量[重复]【英文标题】:Variables are not being set inside the .then() part of a Promise [duplicate] 【发布时间】:2018-04-17 04:20:36 【问题描述】:

我对 javascript 和 node.js 还很陌生,因此当我的机器人需要运行时,被投入 Promises 是相当令人生畏的。

var storedUserID;
ROBLOX.getIdFromUsername(accountArg).then(function(userID) 
  message.reply("your id is " + userID);
  storedUserID = userID;
);
message.reply(storedUserID);

这基本上就是我写的内容,它创建了一个名为“storedUserID”的变量,我想稍后对其进行更新。我正在尝试在 Promise 中更新它,但它似乎不起作用。

在代码中,有 message.reply("your id is " + userID); 可以按预期工作。它将打印给用户“您的 id 是 [NUMBER]”,所以我知道 userID 不为空。

但是,当我在 Promise 之外运行 message.reply(storedUserID); 时,由于未保存变量,因此不会打印任何内容。我不知道为什么。

任何帮助将不胜感激,因为这将用于我在大学的工作! 谢谢!

【问题讨论】:

then 是异步运行的。当您记录该回调尚未执行时。 @IngoBürk 请参阅 “我想稍后更新的 OP。” 链接的问答如何演示如何更改 Promise 的值?跨度> 【参考方案1】:

return 函数的值传递给.then()

var storedUserID = ROBLOX.getIdFromUsername(accountArg)
                   .then(function(userID) 
                     return userID;
                   );

然后,您可以在必要时使用或更改 Promise

storedUserID = storedUserID.then(id) 
  return /* change value of Promise `storedUserID` here */
);

.then() 中访问并将值传递给message.reply()

storedUserID.then(function(id) 
  message.reply(id);
);

var storedUserID = ROBLOX.getIdFromUsername(accountArg);
// later in code
storedUserID.then(function(id) 
  message.reply(id);
);

【讨论】:

将承诺映射到自身有什么意义? @IngoBürk 你的意思是更新后的第二个例子吗? 是的。但我的问题是:为什么这是第二种选择?第一个有什么意义? @IngoBürk 要证明Promise 的值可以通过返回不同的值在.then() 处更改,请参阅 处的OP“我想稍后更新。” 啊,我明白了……谢谢!仍然对整个异步事情感到困惑。 :]【参考方案2】:

因为 getIdFromUsername 是异步的,所以在存储 ID 之前运行 message.reply 存储 ID 的最后一行。

getIdFromUsername 等异步函数不会停止以下代码行的运行。如果您希望它在返回 ID 后发生,则需要进入 then 回调。

【讨论】:

以上是关于未在 Promise 的 .then() 部分内设置变量[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Promise.all().then() 解决?

Promise.then(a, b) 和 Promise.then(a).catch(b) 一样吗? [复制]

09 promise then

Promise.then() 在 promise 解决之前执行

Promise 中的 then总结

手写Promise的实现