js中的promise和async

本文详细介绍了JavaScript中的Promise和async异步编程,包括Promise的.then(), .catch(), .finally()方法及其执行顺序,以及async函数的工作原理。通过多个示例解释了async/await的用法,并解答了关于何时使用Promise、如何中断then块、如何处理Promise链上的错误等常见问题。" 111808683,10325175,Unity实现图片拖拽与拼图游戏,"['Unity3D', '游戏开发', 'GUI交互', '图像处理']
摘要由CSDN通过智能技术生成
  • promise异步类

参考:https://www.runoob.com/js/js-promise.html

Promise 类有 .then() .catch() 和 .finally() 三个方法,这三个方法的参数都是一个函数,.then() 可以将参数中的函数添加到当前 Promise 的正常执行序列,.catch() 则是设定 Promise 的异常处理序列,.finally() 是在 Promise 执行的最后一定会执行的序列。 .then() 传入的函数会按顺序依次执行,有任何异常都会直接跳到 catch 序列:

Promise例子:

const log = console.log;

function getNowTime(now) {
    let tm = new Date(now);
    let arr = [tm.getHours(), tm.getMinutes(), tm.getSeconds()];
    return arr.join(":");
}

new Promise(function(resolve, reject) {
    log("create ", getNowTime(Date.now()));
    setTimeout(function() {
        log("end ", getNowTime(Date.now()));
        resolve("from create");
    }, 3 * 1000);
}).then(function(name) {
    log("then first. name = ", name, ", ", getNowTime(Date.now()));
    return "from first";
}).then(function(name) {
    log("then second. name = ", name, ", ", getNowTime(Date.now()))
    return "from second";
}).then(function(name) {
    log("then third. name = ", name, ", ", getNowTime(Date.now()));
    throw ("exception from third"); //从这里直接抛出异常跳转到finally.
    // return "from third";
}).then(function(name) {
    log("then fourth. name = ", name, ", ", getNowTime(Date.now()));
    return "from fourth";
}).catch(function(name) {
    log("catch name = ", name, ", ", getNowTime(Date.now()));
}).finally(function(name) {
    log("finally name = ", name, ", ", getNowTime(Date.now()));
});

log("main---", getNowTime(Date.now()));

结果:

$ node prm.js
create  15:54:11
main--- 15:54:11
end  15:54:14
then first. name =  from create ,  15:54:14
then second. name =  from first ,  15:54:14
then third. name =  from second ,  15:54:14
catch name =  exception from third ,  15:54:14
finally name =  undefined ,  15:54:14

例子2:

当finally与catch交换次序:

const log = console.log;

function getNowTime(now) {
    let tm = new Date(now);
    let arr = [tm.getHours(), tm.getMinutes(), tm.getSeconds()];
    return arr.join(":");
}

new Promise(function (resolve, reject) {
    log("create ", getNowTime(Date.now()));
    setTimeo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值