JavaScript承诺如何在后台工作 [英] How JavaScript promises work behind the scenes

查看:76
本文介绍了JavaScript承诺如何在后台工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对产生和消费诺言的幕后情况感到非常困惑。请澄清我的观点,并对我的英语不佳表示歉意。

I'm so much confused about what happens behind the scenes when promise is produced and consume. Please clarify my points and sorry for my weak English.


  1. 用新关键字创建空白对象Promise构造函数是
    ,并且是new关键字将Promise构造函数的this设置为
    空白对象this = blankobject。

  2. Promise构造函数在参数
    中接收回调(执行函数)并调用执行函数

  3. 执行器函数接收两个回调(resolve,reject)作为参数

  4. setTimeout在执行器函数中被调用,并且setTimeOut是
    异步代码

  5. 异步代码转到后台,然后Promise构造函数返回
    Promise对象(原为空白对象),而Promise对象引用
    保存到myPromise。

  6. 已创建变量

  1. blank object is created with new keyword Promise constructor is called and new keyword set the this of Promise constructor points to the blank object this = blankobject.
  2. Promise constructor receives callback (executor function) in argument and calls the executor function.
  3. executor function receives two callbacks (resolve,reject) as arguments
  4. setTimeout gets called in the executor function and setTimeOut is async code
  5. async code goes to background and then Promise constructor returns Promise object formerly blank object and Promise object reference saved to myPromise.
  6. a variable is created

接下来会发生什么?当调用 then 方法时, then 方法的代码进入后台吗?我想它会进入后台并且变量是console.log // 10

What happens next ? When then method is called the code of then method goes to background? I imagine it goes to background and a variable is console.log // 10

在主代码执行完成后,异步代码开始 setTimeout 回调开始执行,执行完成后将兑现诺言,并且已解决的函数返回值。此值如何存储在Promise对象中,以及 then 方法中会发生什么?

After main code execution finishes, async code start setTimeout callback begins to execute and after execution finishes promise is fulfilled and resolved function returns value. How is this value stored in promise object and what happens in then method ?

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)


推荐答案

以下是内置承诺类捕获最终尚未实施。

The following is a simplified implementation of the built-in Promise class. catch and finally have not been implemented.

提供给Promise构造函数的函数称为执行程序函数,并立即且同步地调用。

The function supplied to the Promise constructor is called the executor function, and is invoked immediately and synchronously.

每个诺言都有一个方法,然后启用诺言链。

Every promise has a method .then, enabling the chaining of promises.

提供给的功能。然后 总是在微任务上异步调用(请注意使用 queueMicrotask 以下)。

Functions supplied to .then are always invoked asynchronously on a microtask (note use of queueMicrotask below).

每次。然后调用,创建并返回新的诺言。

Every time .then is called, a new promise is created and returned.

。然后可以在同一promise上多次调用,创建promise结果的多播,并分支promise

.then can be called more than once on the same promise, creating a multicast of the result of the promise, and a branching of the promise chain.

一个承诺可以处于以下三个状态之一:未决,已实现或被拒绝。状态转换是单向的:您不能从已实现或被拒绝转变为待处理。

A promise can be in one of three states: pending, fulfilled, or rejected. State transitions are unidirectional: you cannot move from fulfilled or rejected, back to pending.

如果一个承诺被另一个承诺解决,则两个承诺链将连接在一起,并且外部承诺承担内部承诺的状态(可能处于待处理状态),直到内部承诺解决为止。

If a promise is resolved with another promise, then the two promise chains are joined and the outer promise takes on the status of the inner promise (which could be pending), until the inner promise resolves.

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)

请参见

这篇关于JavaScript承诺如何在后台工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆