javascript Promise vs Async&Await

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Promise vs Async&Await相关的知识,希望对你有一定的参考价值。

slowMath.add(6, 2)                         // 1. add together 6 & 2 = 8
 .then((num1) => {
    let num2 = slowMath.multiply(num1, 2);                  // 2. multiply 8 by 2 = 16
    return num2;
}).then((num2) => {
    console.log(num2);
    let num3 = slowMath.divide(num2, 4);                    // 3. divide 16 by 4 = 4
    return num3;
}).then((num3) => {
    console.log(num3);
    let num4 = slowMath.subtract(num3, 3);                   // 4. subtract 3 from 4 = 1
    return num4;
}).then((num4) => {
    console.log(num4);
    let num5 = slowMath.add(num4, 98);                      // 5. add 1 and 98 = 99
    return num5;
}).then((num5) => {
    console.log(num5);
    let num6 = slowMath.remainder(num5, 2);                 // 6. 99 / 2 = remainder 1
    return num6;
}).then((num6) => {
    console.log(num6);
    let num7 = slowMath.multiply(num6, 50);                 // 7. multiply 1 by 50 = 50
    return num7;
}).then((num7) => {
    console.log(num7);
    let num8 = slowMath.remainder(num7, 40);                // 8. 50 / 40 = remainder 10
    return num8;
}).then((num8) => {
    console.log(num8);
    let num9 = slowMath.add(num8, 32);                      // 9. add 10 and 32 = 42
    return num9;
}).then((num9) => {
    console.log(num9);
    console.log(`The final result is ${num9}.`);
}).catch((err) => {
    console.log(err);
});
// Async and Await practice

async function promiseChain() {
    try {
    let num1 = await slowMath.add(6, 2);
        console.log(num1);
    let num2 = await slowMath.multiply(num1, 2);
        console.log(num2);
    let num3 = await slowMath.divide(num2, 4);  
        console.log(num3);
    let num4 = await slowMath.subtract(num3, 3); 
        console.log(num4);
    let num5 = await slowMath.add(num4, 98);
        console.log(num5);
    let num6 = await slowMath.remainder(num5, 2);
        console.log(num6);
    let num7 = await slowMath.multiply(num6, 50); 
        console.log(num7);
    let num8 = await slowMath.remainder(num7, 40);
        console.log(num8);
    let num9 = await slowMath.add(num8, 32);  
        console.log(num9);
        console.log(`The final result is ${num9}.`);
    } catch (e) {
        console.log(e);
    };
    };

    promiseChain();

以上是关于javascript Promise vs Async&Await的主要内容,如果未能解决你的问题,请参考以下文章

javascript [JS] Promise VS Async / Await

《你不知道的JavaScript》三卷读后感

Javascript 异步函数的“等待”的正确心智模型:生成器的“产量”与“promise.then()”?

Vue数据请求 axios vs fetch

promise VS future

Promise.resolve().then vs setImmediate vs nextTick