SetTimeout with Promise.resolve 输出的不是字符串,而是字符串的数值,为什么?
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()
没有 "just work" 承诺。您必须像这样使用字符串值解决承诺,并将您的输出记录在 .then()
:
中
const good = new Promise(resolve => {
setTimeout(resolve, 4000, 'success');
});
good.then(result => {
console.log(result);
});
承诺不会 return 明确的价值。它 return 是一个已解决或已拒绝的承诺对象。更多地研究 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
我正在尝试使用 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()
没有 "just work" 承诺。您必须像这样使用字符串值解决承诺,并将您的输出记录在 .then()
:
const good = new Promise(resolve => {
setTimeout(resolve, 4000, 'success');
});
good.then(result => {
console.log(result);
});
承诺不会 return 明确的价值。它 return 是一个已解决或已拒绝的承诺对象。更多地研究 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