美文网首页
promise async await的理解和使用

promise async await的理解和使用

作者: ironman_ | 来源:发表于2017-10-17 23:56 被阅读0次

    个人理解:
    因为javascript是单线程的,所以他的异步相当于将一些任务丢到运行队列的尾部,就像是Android里post一个runnable到MessageQueue的尾部,但是当前的代码继续执行。

    promise

    Promise 对象用于一个异步操作的最终完成(或失败)及其结果值的表示。(简单点说就是处理异步请求。我们经常会做些承诺,如果我赢了你就嫁给我,如果输了我就嫁给你之类的诺言。这就是promise的中文含义:诺言,一个成功,一个失败。)

    语法:

    new Promise(
        /* executor */
        function(resolve, reject) {...}
    );
    

    参数:
    executor

    executor是一个带有 resolve 和 reject 两个参数的函数 。executor 函数在Promise构造函数执行时同步执行,被传递 resolve 和 reject 函数(executor 函数在Promise构造函数返回新建对象前被调用)。resolve 和 reject 函数被调用时,分别将promise的状态改为fulfilled(完成)或rejected(失败)。executor 内部通常会执行一些异步操作,一旦完成,可以调用resolve函数来将promise状态改成fulfilled,或者在发生错误时将它的状态改为rejected。

    如果在executor函数中抛出一个错误,那么该promise 状态为rejected。executor函数的返回值被忽略。

    参考链接:
    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

    async 和 await

    async表示一个函数是一个异步方法

    When an async function is called, it returns a Promise. When the async function returns a value, the Promise will be resolved with the returned value. When the asyncfunction throws an exception or some value, the Promise will be rejected with the thrown value.

    An async function can contain an await expression, that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

    async方法被被调用会返回一个promise,当async方法自己返回的时候,这个promise就有值了。
    await关键字会阻断方法的执行,等待promise完成,然后继续执行。这个等待是async方法内的等待,方法外部还是继续执行(比如下面的最后一个printLog语句)。

    example:

    function resolveAfter2Seconds(x) {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve(x);
            }, 2000);
        });
    }
    
    async function add1(x) {
        printLogWithTime("add1 start");
        const a = await resolveAfter2Seconds(20);
        printLogWithTime("add1 start a");
        const b = await resolveAfter2Seconds(30);
        printLogWithTime("add1 start b");
        return x + a + b;
    }
    
    add1(10).then(v => {
        console.log(v);  // prints 60 after 4 seconds.
    });
    //虽然上面阻塞了,但是这里继续执行
    printLogWithTime("end of the code");
    
    function printLogWithTime(tag) {
        let currentDate = new Date();
        let time = currentDate.getMinutes() + ":" + currentDate.getSeconds() + ":" + currentDate.getMilliseconds();
        console.log(time+" "+tag);
    }
    

    输出结果:

    16:6:50 add1 start
    16:6:56 end of the code
    16:8:61 add1 start a
    16:10:64 add1 start b
    60
    

    参考文档:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

    相关文章

      网友评论

          本文标题:promise async await的理解和使用

          本文链接:https://www.haomeiwen.com/subject/wjajuxtx.html