【问题标题】:Is Promise a technique to realize asynchronous programming?Promise 是一种实现异步编程的技术吗?
【发布时间】:2019-08-19 12:56:16
【问题描述】:

我试图理解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依次执行) .

【问题讨论】:

标签: javascript node.js asynchronous es6-promise


【解决方案1】:

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

这是否意味着:Promise 只是用来承诺 function2 在 function1 之后执行?

没错,即使 function1 异步返回它的值(通过 Promise),function2 只有在该值存在时才会运行。

实现“异步”不是技术,而是实现“同步”[执行]的方法?

不是真的。将已经存在的值包装到 Promise 中是没有意义的。将一个将“异步”回调的回调包装到一个 Promise 中是有意义的。也就是说,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);

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

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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 2015-06-15
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    相关资源
    最近更新 更多