【问题标题】:resolving promise from another function从另一个函数解决承诺
【发布时间】:2017-11-14 17:14:31
【问题描述】:

函数内部的 Promise 链是如何工作的? 在以下代码中:

     promiseA() {
            return anotherPromise().then( res => {
                   // resolution of promise A
             })
     };


      promiseB() {
             promiseA().then( res => {
                     // resolution of promise B
              })
      }

我测试了这段代码,我发现 B 的解析总是在 A 被解析后完成。但是,我找不到任何文档。承诺 B 的解决是否总是在承诺 A 的解决之后发生,或者我的测试只是竞争条件的一种情况?

【问题讨论】:

  • 有没有功能都无所谓。 then 表示在promise解析后执行。
  • 那么在这种情况下,是先解决A然后再解决B吗? @estus
  • 是的,这就是then的目的。

标签: angular typescript promise


【解决方案1】:

是的,它总是会在 B 之前先解决 A。如果您在没有间接方法的情况下重新编写代码,那么您所拥有的就是:

anotherPromise().then(...A...).then(...B...)

这应该清楚地表明,A then 内的代码必须始终在 B then 内的代码之前运行。

一个简单的测试证实。你可以运行一百万次,A 总是在 B 之前解决:

function anotherPromise(){
  return new Promise((resolve,reject) => {
  	setTimeout(resolve,1000);
  });
}

function promiseA(){
   return anotherPromise().then( res => {
      console.log("Resolve promiseA");
      return res;
  });
}

function promiseB(){
    return promiseA().then(res => {
    	console.log("Resolve promiseB");
      return res;
    })
}

promiseB();

【讨论】:

    【解决方案2】:

    你已经在 Promise B 中调用了 Promise A,所以从逻辑上讲,Promise A 应该在 Promise B 之前解决。

    Promise.then( // resolved first )
           .then( // resolved second )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-17
      • 2013-07-02
      • 1970-01-01
      • 2022-11-22
      相关资源
      最近更新 更多