zoukankan      html  css  js  c++  java
  • Promise对象

    一、Promise 有三个状态

      1、pending(进行中)

      2、fulfilled(已成功)

      3、rejected(已失败)

    案例1

    function  delayFn () {
        return new Promise((resolve, reject) => {
            setTimeout (() => {
                resolve()
            },3000)
        })
    }
    delayFn().then(() => {
        console.log('dfdfdf')
    }).catch(err => {
        console.log(err)
    })
    View Code

     案例2 (Promise.all() 并发执行

    function fn1 () {
        return new Promise((resolve, reject) =>{
            resolve('one')
        }).catch(err => {
            throw new Error(err)
        })
    }
    function fn2 () {
        return new Promise((resolve, reject) =>{
            resolve('two')
        }).catch(err => {
            throw new Error(err)
        })
    }
    let res = Promise.all([fn1(), fn2()])
    res.then(v =>{
        console.log(v)
    })
    View Code

    案例3 (异步超时,取消用Promise.race()

    function fn1() {
        return new Promise((resolve, reject) => {
            setTimeout(function() {
                resolve('finish')
            }, 3000);
        });
    }
    function cancel() {
        return new Promise((resolve, reject) => {
            setTimeout(function() {
                resolve('超时了')
            }, 1000);
        });
    }
    let promise = Promise.race([fn1(), cancel()])
    promise.then((value) => {
            console.log(value) // -> 超时了
    })
    View Code
  • 相关阅读:
    NOIP 2012 文化之旅
    史上最全的各种C++ STL容器全解析
    详解C++ STL map 容器
    详解C++ STL priority_queue 容器
    浅谈C++ STL stack 容器
    浅谈C++ STL queue 容器
    浅谈C++ STL vector 容器
    CF1185F Two Pizzas
    浅谈C++ STL deque 容器
    详解C++ STL multiset 容器
  • 原文地址:https://www.cnblogs.com/vhen/p/7574925.html
Copyright © 2011-2022 走看看