当 Promise 产生和消费时,我对幕后发生的事情感到非常困惑。请澄清我的观点,并为我的英语不好感到抱歉。
调用和 new 关键字设置 Promise 构造函数指向的 this
空白对象 this = blankobject。
并调用执行器函数。
异步代码
Promise 对象以前是空白对象和 Promise 对象引用
保存到 myPromise。
接下来发生什么 ?当
then
方法被称为 then
的代码方法进入后台?我想它会进入后台,变量是 console.log//10主代码执行完成后,异步代码开始
setTimeout
回调开始执行,执行完成后,promise 被实现,resolved 函数返回值。这个值如何存储在 Promise 对象中以及在 then
中发生了什么方法 ?let myPromise = new Promise (
(resolve, reject) => {
setTimeout(() => {
console.log(getIDs)
resolve(10);
}, 1500);
}
)
let a = 10
myPromise.then(val => {
console.log(val);
})
console.log(a)
最佳答案
以下是内置 Promise class 的简化实现. catch
和 finally
尚未实现。
提供给 Promise 构造函数的函数称为 executor 函数,并立即同步调用。
每个 promise 都有一个方法 .then
,启用 promise 的链接。
提供给 .then
的函数总是在微任务上异步调用 (注意使用下面的 queueMicrotask
)。
每次.then
被调用,一个新的 Promise 被创建并返回。.then
可以在同一个 Promise 上多次调用,创建 Promise 结果的多播,以及 Promise 链的分支。
Promise 可以处于以下三种状态之一:待处理、已完成或已拒绝。状态转换是单向的:您不能从已完成或已拒绝,回到待处理状态。
如果一个 Promise 与另一个 Promise 一起解决,那么两个 Promise 链会连接起来,并且外部 Promise 会采用内部 Promise 的状态(可能是待处理的),直到内部 Promise 解决。
function Promise(executor) {
if (!executor) throw "Promise executor undefined"
let status = "pending", value, thenQ = []
const then = onFulfilled => {
let resolver
// This ensures control does not move to later promises
// until prior promises have been resolved.
const nextPromise = new Promise(resolve => (resolver = resolve))
// More than one "then" can be registered with each promise.
thenQ.push((...args) => resolver(onFulfilled(...args)))
return nextPromise
}
// We check if the result is a "thenable"; if so, we treat
// it as an inner promise, otherwise we simply fulfil with
// the result.
const resolve = result => result?.then ? result.then(fulfil) : fulfil(result)
// When a promise has been fulfilled, its "thens" can be run.
const fulfil = result => (status = "fulfilled", value = result, executeThens(value))
// "Thens" are run asynchronously, on a microtask.
const executeThens = value => queueMicrotask(() => thenQ.forEach(el => el(value)))
// The executor is run synchronously.
executor(resolve)
return {
then,
get status() { return status },
get value() { return value }
}
}
// Chaining
new Promise(resolve => {
console.log('Waiting for step 1...')
setTimeout(() => resolve("One, two..."), 1500)
})
.then(result => new Promise(resolve => {
console.log('Waiting for step 2...')
setTimeout(() => resolve(`${result}three, four`), 1500)
}))
.then(result => console.log(`Chaining result: ${result}.`))
// Branching
const p = new Promise(resolve => {
console.log('Waiting for step a...')
setTimeout(() => resolve("Alpha, Bravo..."), 1500)
})
p.then(result => new Promise(resolve => {
console.log('Waiting for step b1...')
setTimeout(() => resolve(`${result}Charlie, Delta`), 1500)
})).then(console.log)
p.then(result => {
console.log('Waiting for step b2...')
return `${result}Echo, Foxtrot`
}).then(console.log)
见 also .
关于javascript - JavaScript Promise 如何在幕后工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61442578/