首页 文章

如何获取承诺的 Value ?

提问于
浏览
75

我'm looking at this example from Angular'的文档'm looking at this example from Angular'但我认为这可能适用于一般的承诺 . 他们有这个例子,逐字复制,其评论包括:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

// promiseB will be resolved immediately after promiseA is resolved and its value
// will be the result of promiseA incremented by 1

我不清楚这是如何工作的 . 如果我可以在第一个 .then() 的结果上调用 .then() ,将它们链接起来,我知道我可以,那么 promiseB 是一个类型为 Object 的promise对象 . 它不是 Number . 那么"its value will be the result of promiseA incremented by 1"是什么意思?

我应该访问 promiseB.value 或类似的东西吗?成功回调如何返回一个承诺并返回"result + 1"?我错过了什么 .

7 回答

  • 13

    promiseAthen 函数返回一个新的promise( promiseB ),它在 promiseA 解析后立即解析,其值是 promiseA 中成功函数返回的值 .

    在这种情况下, promiseA 将使用值_ result 解析,然后立即使用 result + 1 的值解析 promiseB .

    访问 promiseB 的值与访问 promiseA 的结果的方式相同 .

    promiseB.then(function(result) {
        // here you can use the result of promiseB
    });
    
  • 71

    ____________________ promiseB的函数接收promiseA的 .then 函数返回的内容 .

    这里promiseA返回的是一个数字,它将在promiseB的成功函数中以 number 参数的形式提供 . 然后将增加1

  • 2

    解析评论与您目前的理解有所不同可能会有所帮助:

    // promiseB will be resolved immediately after promiseA is resolved
    

    这表明 promiseB 是一个承诺,但会在 promiseA 解决后立即解决 . 查看此方法的另一种方式意味着 promiseA.then() 返回分配给 promiseB 的promise .

    // and its value will be the result of promiseA incremented by 1
    

    这意味着 promiseA 解析为的值是 promiseB 将作为其successCallback值接收的值:

    promiseB.then(function (val) {
      // val is now promiseA's result + 1
    });
    
  • 0
    promiseA(pram).then(
         result => { 
         //make sure promiseA function allready success and response
         //do something here
    }).catch(err => console.log(err)) => {
         // handle error with try catch
    }
    
  • 0

    也许这个小的Typescript代码示例会有所帮助 .

    private getAccount(id: Id) : Account {
        let account = Account.empty();
        this.repository.get(id)
            .then(res => account = res)
            .catch(e => Notices.results(e));
        return account;
    }
    

    这里 repository.get(id) 返回 Promise<Account> . 我将它分配给 then 语句中的变量 account .

  • -3

    当一个promise被解决/拒绝时,它会调用它的成功/错误处理程序:

    var promiseB = promiseA.then(function(result) {
       // do something with result
    });
    

    then 方法还返回一个promise:promiseB,它将被解析/拒绝 depending on the return value from the success/error handler from promiseA .

    promiseA的成功/错误处理程序可以返回三个可能的值,这将影响promiseB的结果:

    1. Return nothing --> PromiseB is resolved immediately, 
       and undefined is passed to the success handler of promiseB
    2. Return a value --> PromiseB is resolved immediately,
       and the value is passed to the success handler of promiseB
    3. Return a promise --> When resolved, promiseB will be resolved. 
       When rejected, promiseB will be rejected. The value passed to
       the promiseB's then handler will be the result of the promise
    

    有了这种理解,您可以理解以下内容:

    promiseB = promiseA.then(function(result) {
      return result + 1;
    });
    

    then调用立即返回promiseB . 当promiseA解决后,它会将结果传递给promiseA的成功处理程序 . 由于返回值是promiseA的结果1,成功处理程序返回一个值(上面的选项2),因此promiseB将立即解析,并且promiseB的成功处理程序将传递promiseA的结果1 .

  • 0

    您可以使用javascript中的异步等待方法轻松完成此操作 .

    下面是使用超时检索WebRTC承诺值的示例 .

    function await_getipv4(timeout = 1000) {
        var t1 = new Date();
        while(!window.ipv4) {
            var stop = new Date() - t1 >= timeout;
            if(stop) {
                console.error('timeout exceeded for await_getipv4.');
                return false;
            }
        }
        return window.ipv4;
    }
    
    function async_getipv4() {
        var ipv4 = null;
        var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){}}})
        findIP.then(ip => window.ipv4 = ip);
        return await_getipv4();
    };
    

相关问题