gpt4 book ai didi

javascript - 对此行为 : ES6 Promise that is never resolved 的解释是什么

转载 作者:行者123 更新时间:2023-11-30 14:07:56 25 4
gpt4 key购买 nike

以下代码:

Promise.resolve('a string')
.then(resp => {
console.log('resp from the initial promise: ' + resp)
const p0 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('finished sleeping in p0')
resolve('hello from p0')
}, 5000)
})
console.log('returning p0')
return p0
})
.then(resp => {
console.log('resp from p0: ' + resp)
const p1 = new Promise((resolve, reject) => {
console.log('p1 completed')
// resolve('another string from p1')
})
console.log('returning p1')
return p1
})
.then(res => {
console.log('resp from p1: ' + res)
})
.catch(err => {
console.error('Error: ' + err.message)
})

console.log('last statement')

当我运行它时,我得到以下输出(这对我来说没有意义)

last statement
resp from the initial promise: a string
returning p0
finished sleeping in p0
resp from p0: hello from p0
p1 completed
returning p1

首先,由于 promise p1 从未得到解决,我希望程序永远等待并且永远不会完成。事实并非如此,它完成得很好(尽管没有到达最后一个 then())。

此外,它还创建 promise 并在 创建 promise 之后的代码之前执行 promise 内的代码。我希望“返回 p1”“p1 完成”之前出现,因为我假设 promise 中的内容将在下一个滴答时执行。

最佳答案

Also, it creates the promise and executes the code inside of the promise before the code that comes after it's created. I would expect 'returning p1' to come before 'p1 completed' since I assumed that what's inside the promise would be executed on the next tick.

如果您在一个 promise 上调用 .then,您传入的函数将延迟到下一个 tick。但是 promise 的构造函数不会那样做。当您构造一个 new Promise 时,您传递给构造函数的代码会立即同步运行。所以这段代码:

const p0 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('finished sleeping in p0')
resolve('hello from p0')
}, 5000)
})
console.log('returning p0')

... 将立即设置超时,甚至在 promise 被分配给 p0 之前。这段代码:

const p1 = new Promise((resolve, reject) => {
console.log('p1 completed')
// resolve('another string from p1')
})
console.log('returning p1')

... 将立即注销“p1 已完成”,甚至在 promise 被分配给 p1 之前。

关于javascript - 对此行为 : ES6 Promise that is never resolved 的解释是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55052638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com