gpt4 book ai didi

javascript - 异步函数是 JavaScript 中函数的子集吗?

转载 作者:行者123 更新时间:2023-11-28 12:15:23 25 4
gpt4 key购买 nike

据我所知,async function 表达式返回一个 AsyncFunction 对象。

  1. AsyncFunction 是否继承 Function
  2. 可以使用异步函数代替函数吗? (例如作为回调参数)如果不是,可能存在什么陷阱?

最佳答案

异步函数基本上只是一个自动转换为返回 promise 而不是普通值的函数。它还可以在内部使用 await 作为解析另一个异步函数返回的 Promise 的简写。

  1. 是的。如下所示,它的类型是function,它是Function的一个实例。

async function afunc() {
return 3;
}

console.log(typeof afunc);
console.log(afunc instanceof Function);

  • 是的,您可以将其用作回调。 MDN显示了将异步函数与 setTimeout 结合使用的示例。
  • var resolveAfter2Seconds = function() {
    console.log("starting slow promise");
    return new Promise(resolve => {
    setTimeout(function() {
    resolve(20);
    console.log("slow promise is done");
    }, 2000);
    });
    };

    var resolveAfter1Second = function() {
    console.log("starting fast promise");
    return new Promise(resolve => {
    setTimeout(function() {
    resolve(10);
    console.log("fast promise is done");
    }, 1000);
    });
    };

    var sequentialStart = async function() {
    console.log('==SEQUENTIAL START==');
    const slow = await resolveAfter2Seconds(); // If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.
    const fast = await resolveAfter1Second();
    console.log(slow);
    console.log(fast);
    }

    var concurrentStart = async function() {
    console.log('==CONCURRENT START with await==');
    const slow = resolveAfter2Seconds(); // starts timer immediately
    const fast = resolveAfter1Second();

    console.log(await slow);
    console.log(await fast); // waits for slow to finish, even though fast is already done!
    }

    var stillSerial = function() {
    console.log('==CONCURRENT START with Promise.all==');
    Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then(([slow, fast]) => {
    console.log(slow);
    console.log(fast);
    });
    }

    var parallel = function() {
    console.log('==PARALLEL with Promise.then==');
    resolveAfter2Seconds().then((message)=>console.log(message)); // in this case could be simply written as console.log(resolveAfter2Seconds());
    resolveAfter1Second().then((message)=>console.log(message));
    }

    sequentialStart(); // takes 2+1 seconds in total
    // wait above to finish
    setTimeout(concurrentStart, 4000); // takes 2 seconds in total
    // wait again
    setTimeout(stillSerial, 7000); // same as before
    // wait again
    setTimeout(parallel, 10000); // trully parallel

    关于javascript - 异步函数是 JavaScript 中函数的子集吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50868014/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com