繁体   English   中英

关于链接es6 Promises,then()和价值消耗

[英]About chaining es6 Promises, then() and value consumption

这与ES6 Promise中的Chaining .then()调用紧密相关...

我尝试使用一些组成承诺链的函数来进行此操作,基本上是这样的:

var PromiseGeneratingMethod = function(){
  return p = new Promise((resolve, reject) =>{
    resolve(1)
  });
}

var inBetweenMethod = function(){
  return PromiseGeneratingMethod()
    .then((resolved) => {
    if(resolved){
      console.log('resolved in between');
      //return resolved
        /* this changes output to
        resolved in between
        resolved at last*/
    }else{
      console.log('something went terribly wrong in betweeen', resolved);
    }
  });
}

inBetweenMethod().then((resolved) =>{
  if(resolved){
    console.log('resolved at last')
  }else{
    console.log('something went terribly wrong', resolved);
  }
})

/* ouput: 
resolved in between
something went terribly wrong undefined*/

我不明白为什么会这样。 没有一个Promise仅一个关联的返回值? 为什么每次都可以更改该值? 对我来说似乎不合理。 一个Promise对象只能有一个返回值,我想在Promise得到解决后,每个处理程序都会收到相同的参数吗?

这样,在同一个Promise上有两个调用then()的方法,后一个(在异步环境中,您永远不知道那是什么...)总是会得到一个空的结果,除非每一个都返回期望的值

如果我做对了,唯一的好处是您可以构建一个then()。then()。then()链使其几乎同步(通过在每个then()中返回任意值),但是您仍然可以实现嵌套的Promises也一样,对吗?

有人可以帮助我理解es6 Promises为什么以这种方式工作,以及是否还有更多使用这些警告的注意事项?

没有一个承诺只是一个关联的返回值?

是。

为什么每次都可以更改该值?

因为每个.then()调用都会返回一个新的 Promise。

有两个在同一个Promise上调用then()的方法

那不是你在做什么。 then您的回调将安装在不同的 Promise中,这就是它们获得不同值的原因。

可以

function inBetweenMethod() {
  var promise = PromiseGeneratingMethod();
  promise.then(resolved => { … }); // return value is ignored
  return promise;
}

但您应该避免这种情况。 您已经注意到,可以通过以下方式获得预期的行为

function inBetweenMethod() {
  var promise = PromiseGeneratingMethod();
  var newPromise = promise.then(value => {
     …
     return value;
  });
  return newPromise;
}

在这里, newPromise将使用回调返回的值进行解析-可能与promise实现的值相同。

您两次使用.then()处理函数,请执行以下操作:

var PromiseGeneratingMethod = function(){
  return new Promise((resolve, reject) =>{
    if (myCondition) resolve(1)
    if (!myCondition) reject("failed")
  });
}

var inBetweenMethod = function(){
  return PromiseGeneratingMethod()
}

inBetweenMethod().then((resolved) =>{
  console.log(resolved)
}).catch(function(err) {
  console.log(err)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM