繁体   English   中英

带有Promise.resolve的SetTimeout不输出字符串,而是输出字符串的数值,为什么?

[英]SetTimeout with Promise.resolve not outputting string but a numerical value of string, why?

我正在尝试使用具有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"

当我查看此内容时,似乎并不可行,但这是挑战,因此我发现自己缺少了一些东西。

我希望这有助于澄清问题

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

 const good = new Promise(resolve => { setTimeout(resolve, 4000, 'success'); }); good.then(result => { console.log(result); }); 

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

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

如果要定义良好,则必须在promise的then区块中进行。 但是要注意,如果您尝试在承诺之外使用好东西,它可能会重新定义。

 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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM