javascript - A little doubt about Promise
为情所困
为情所困 2017-05-19 10:36:01
0
2
436
 var p = new Promise((resolve, reject) => {  
     //这里的参数若是thenable的,规范有提到加入job队列,必然是异步的
     //但是比如参数是数字,在返回promise之前,就已经修改了它的状态,这样似乎是同步的了
     resolve(3);
 });
 console.dir(p.[[state]]);

Is the above code synchronous? That is, if there is p.[[state]], then fulfilled should be printed instead of pendding.

p.thenThe callback function in the method is asynchronous, so there should be no problem

为情所困
为情所困

reply all(2)
我想大声告诉你

This is undoubtedly synchronized.

曾经蜡笔没有小新

This code of yours is indeed synchronized, there is a simple way to verify it

const p = new Promise((resolve, reject) => {
  console.log('in')
  resolve(3)
})
console.log(p)

Look at the above code. Does it type 'in' first? This means that the resolve and reject execution of new Promise are synchronous. If you want to make it asynchronous, you can write it as follows:

const p = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('in')
    resolve(3)
  }, 0)

})
console.log(p)

In addition, the execution of then is indeed asynchronous and can also be verified using a similar method.

By the way, Promise has a commonly used pattern, which wraps synchronization results into Promise to eliminate the difference between synchronous and asynchronous calls:

const addOne = num => Promise.resolve(num + 1)
const addOneAsync = num => new Promise(resolve => setTimeout(resolve(num + 1), 0))

addOne(1).then(n => console.log(n))
addOneAsync(1).then(n => console.log(n))
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template