【问题标题】:SetTimeout with Promise.resolve not outputting string but a numerical value of string, why?SetTimeout with Promise.resolve 不是输出字符串而是输出字符串的数值,为什么?
【发布时间】:2018-10-30 17:23:58
【问题描述】:

我正在尝试使用具有 Promise.resolve 格式的 setTimeout 方法。我想我快要得到它了,但我没有在我的控制台中得到我所期望的。

const good = Promise.resolve(setTimeout(() => 'success', 4000));
console.log(good);

//prints '51' instead of 'success'

我认为'51'是成功的数值。如果我是正确的,我想知道如果它在引号中,为什么它会打印它而不是字符串 isteald。

提前感谢您的帮助!

编辑:澄清一下,这是 Udemy 讲师给我的挑战。我在问为什么我的特定代码不起作用而不是答案。

这是挑战:

const success = new Promise((resolve, reject) => {
         if (true) {
             setTimeout(resolve, 4000, 'success')
         } else {
             reject('error it broke')
         }
     });

    success 
        .then (() => console.log('success!'))


3. Read about Promise.resolve() and Promise.reject(). How can you make 
the above promise shorter with Promise.resolve() and console log "success"

当我查找这个时,这似乎并不可行,但这是一个挑战,所以我认为我错过了一些东西。

我希望这有助于澄清事情

【问题讨论】:

  • 我希望它打印Promise<51>,实际上。而setTimeout()的返回值是一个句柄,你可以传递给clearTimeout()
  • 当你 console.log 的时候,输出是什么?我希望它返回一个已解决的承诺?
  • 我将得到的输出作为注释包含在@EddieDelRio 的代码中。

标签: javascript promise settimeout


【解决方案1】:

setTimeout() 不能“只工作”与承诺。你必须用这样的字符串值解决一个promise,并在.then()中记录你的输出:

const good = new Promise(resolve => {
  setTimeout(resolve, 4000, 'success');
});

good.then(result => {
  console.log(result);
});

【讨论】:

  • 我编辑了我的帖子来解释为什么我试图用 Promises.resolve 编写我的函数
  • 您不能将Promise.resolve() 与异步回调样式函数一起使用。 Promise.resolve() 用于将 同步 值转换为立即解决的承诺。不管怎样,这肯定比你提供的编辑要短。
  • 但我可以使用 Promise.resolve() 来处理已经执行的 Promise 不,这不是 Promise.resolve() 的用途。您应该阅读那里的文档。如果您希望将值 'success' 转换为 Promise,您可以执行 Promise.resolve('success').then(result => ...),但如果您希望在 4 秒后将值 'success',您不能使用Promise.resolve()
  • 非常感谢您为我澄清@PatrickRoberts,由于您的深入解释,我非常感谢这次学习经历。它帮了我很多,你所说的对我来说更有意义,因为从我看到的例子中,我没有看到使用 Promise.resolve 设置 setTimeout 的地方,但这个问题让我很困惑。我肯定会查看文档,感谢您对我的耐心
  • @A-Bro 我会对在线教程持保留态度。您可以从 MDN 之类的文档以及 Stack Overflow 上的提问中获得更多关于 JavaScript 的可靠信息。关于承诺,我想说Bergi 是这里最好的用户之一。如果您想更深入地了解 Promise 的工作原理,请查看他的一些答案。
【解决方案2】:

Promise 不会返回显式值。它返回一个已解决或已拒绝的承诺对象。更多地研究使用 js 的异步操作。但与此同时,请尝试

good.then(expectedGoodValue => console.log(expectedGoodValue));

如果你想定义好的,你必须在承诺的then 块中进行。但是请注意,如果您尝试在 promise 之外使用 good,它可能会返回 undefined。

var good;

new  Promise.resolve(setTimeout(() => 'success', 4000))
.then(value => 
{
  good = value;
})
.then(() =>
{
  //some other operation
  console.log(good); //Won't be undefined
});


console.log(good); //More than likely will be undefined. This line may be hit before the async resolves

【讨论】:

    猜你喜欢
    • 2020-01-10
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 2013-04-30
    • 2017-03-16
    相关资源
    最近更新 更多