Promise是一种实现异步编程的技术吗?

Is Promise a technique to realize asynchronous programming?

我试着去了解 Promise 来自 google 源代码,还没有找到它是如何异步执行代码的。

我对异步函数的理解是它下面的代码可以在它之前一次解析。

例如:

setTimeout(()=>{console.log("in")}, 5000);
console.log("out");

// output:
// out
// in

第二行在第一行之前完成,所以我认为setTimeout是一种异步技术。但是看到这段代码 Promise:

let p = new Promise((resolve, reject)=>{console.log('in'); resolve(1);});
console.log("out");

//in
//out

这个代码块实际上是逐行执行的,如果console.log('in');是一个耗时的操作,第二行将被阻塞直到解决。

我们通常这样使用Promise

(new Promise(function1)).then(function2).then(function3)

是不是说:Promise只是用来保证function2在function1之后执行,并不是实现asynchronous的技术,而是实现synchronous的方法(function1 , function2, function3 依次执行)。

承诺只是一种描述尚不存在但稍后会到达的值的方式。您可以将 .then 处理程序附加到它,以便在发生这种情况时得到通知。

Does this mean: Promise is just used to promise that function2 is executed after function1?

是的,即使 function1 returns 它是异步值(通过 Promise),function2 也会 运行 仅当该值存在时。

it's not a tech to realize 'asynchronous' but a method to realize 'synchronous' [execution] ?

不是真的。将一个已经存在的值包装到一个 promise 中是没有意义的。将回调 "asynchronously" 包装到承诺中是有意义的。也就是说,Promise 本身并不表示它所解析的值是以同步还是异步方式检索的。

function retrieveStuffAsynchronously() {
   // direclty returns a Promise, which will then resolve with the retrieved value somewhen:
   return new Promise((resolve, reject) => {
      // directly executes this, the async action gets started below:
      setTimeout(() => { // the first async code, this gets executed somewhen
         resolve("the value"); // resolves asynchronously
      }, 1000);
   });
}

console.log(retrieveStuffAsynchronously()); // does return a promise immeadiately, however that promise is still pending
retrieveStuffAsynchronously().then(console.log);


旁注:但是,承诺保证异步解决:

const promise = new Promise((resolve, reject)=>{
  console.log('one'); 
  resolve('three');
});

promise.then(console.log); // guaranteed to be called asynchronously (not now)

console.log("two");