@[toc]

Promise

Three states

  • Pending -> Resolved -> or Pending -> Rejected

  • Irreversible change

const p1 = new Promise((resolve, reject) = >{})console.log("p1", p1)

const p2 = new Promise((resolve, reject) = > {
    setTimeout((a)= >{ resolve(); })})console.log("p2", p2)
setTimeout((a)= > console.log("p2-setTimeout", p2))


const p3 = new Promise((resolve, reject) = > {
    setTimeout((a)= >{ reject(); })})console.log("p3", p3)
setTimeout((a)= > console.log("p3-setTimeout", p3))

Copy the code

Performance of state

  • Pending states do not trigger THEN and catch
  • Resolve triggers then and catch
  • Reject triggers a catch

Change states of then and catch

  • Resolved then Return Rejected when the error message is returned
  • ‘Catch’ returns’ Resolved ‘and’ Rejected ‘when an error is reported
const p1 = Promise.resolve().then((a)= > {
    return 100;
});
console.log("p1", p1);

p1.then((a)= > {
    console.log("p1 then");
});

const p2 = Promise.resolve().then((a)= > {
    throw new Error("then error");
});
console.log("p2", p2);

p2.then((a)= > {
    console.log("p2 then");
}).catch((err) = > {
    console.log("p2 catch error", err);
});


const p3 = Promise.reject("p3 error").catch(err= > {
    console.error(err);

});
console.log("p3", p3);  Resolved to trigger a then callback
p3.then((a)= > {
    console.log("p3 then");
});

const p4 = Promise.reject("p3 error").catch(err= > {
    throw new Error("p4 catch error");

});
console.log("p4", p4);  // Rejected triggers a catch callback
p4.then((a)= > {
    console.log("p4 then"); // Can't print
}).catch((err) = > {
    console.log("p4 catch", err);
});
Copy the code

Promise the topic

Promise.resolve().then((a)= > {
    console.log(1);
}).catch((a)= > {
    console.log(2);
}).then((a)= > {
    console.log(3);
})
12
Copy the code
Promise.resolve().then((a)= > {	// Return rejected
    console.log(1);
    throw new Error("error1");
}).catch((a)= > {	// Return resolved with no error
    console.log(2);
}).then((a)= > {
    console.log(3);
})
123
Copy the code
Promise.resolve().then((a)= > {
    console.log(1);
    throw new Error("error1");
}).catch((a)= > {
    console.log(2);
}).catch((a)= > {
    console.log(3);
})
12
Copy the code

async-await

Asynchronous development

  1. Asynchronous callback callback and hell

Problem: Callback hell

  1. Promise then catch chain-call, but also based on callback functions

  2. Async-await is synchronous syntax and eliminates callback functions completely

Basic usage of async-await

  1. Await followed by the Promise function
  2. Await followed by async function

Relationship between async-await and Promise

  • Async-await is the ultimate means of eliminating asynchronous callbacks

  • But Promise and Promise aren’t mutually exclusive, they complement each other

  • An async function must return a Promise object

  • Try-catch catches exceptions instead of. Catch

An async execution must return a Promise object

async function fn1() {
    // return Promise. Resolve ("fn1")
    return Promise.resolve(200);
}
const res1 = fn1();
console.log(res1);

res1.then(data= > {
    console.log("res1 data", data);
});
Copy the code

Await = then()

(async function () {
    const p1 = Promise.resolve(300);
    const data = await p1;
    console.log("data", data); }) (); (async function () {
    const p1 = await 400; // equivalent to await promise.resolve (400)
    const data = await p1;
    console.log("data", data); }) ();Copy the code
(async function () {
    const p1 = await fn1();	
    const data = await p1;
    console.log("data", data); }) ();Copy the code

try-catch

(async function () {
    const p4 = Promise.reject("err");
    try{
        const res = await p4;
        console.log(res);
    }catch (err) {
        console.log("err1", err)
    }
})();

(async function () {
    const p5 = Promise.reject("err");
    const res = await p4;   // This parameter is rejected and try-catch is rejected
    console.log(res)
})();
Copy the code

The nature of asynchrony is still callback functions

  • Js is single threaded and asynchrony is based on Event loop
  • Async await is just a syntactic sugar
async function async1() {
    console.log("async1 start");
    await async2();
    The following lines of // await will become asynchronous
    console.log("async1 end");
}

async function async2() {
    console.log("async2");
}

console.log("script start");
async1();
console.log("script end");
Copy the code

print

script start
async1 start
async2
script end
async1 end
Copy the code

Finish the synchronization code first

Start the event loop

Executing asynchronous code

Add async function

async function async1() {
    console.log("async1 start");
    await async2();
    console.log("async1 end");
    await async3();
    console.log("async1 end 2");
}

async function async2() {
    console.log("async2");
}

async function async3() {
    console.log("async3");

}

console.log("script start");
async1();
console.log("script end");
Copy the code

print

script start
async1 start
async2
script end
async1 end
async3
async1 end 2
Copy the code

Application scenarios of for-OF

  • For-in is a regular synchronous traversal
  • For-of is often used for asynchronous traversal

The code for ordinary asynchronous traversal is as follows

function muti(num) {
    return new Promise(resolve= > {
        setTimeout((a)= > {
            resolve(num * num);
        }, 1000);
    });
}

const nums = [1.2.3];

nums.forEach(async (i) => {
    const res = await muti(i);
    console.log(res);
});
Copy the code

Print them all at the same time after 1s

If you want to print one at a time one second at a time you need to use for-of

Note that await needs to be wrapped with async function to execute

function muti(num) {
    return new Promise(resolve= > {
        setTimeout((a)= > {
            resolve(num * num);
        }, 1000);
    });
}

const nums = [1.2.3]; ! (async function () {
    for (let i of nums) {
        const res = await muti(i);
        console.log(res);
    }
})();
Copy the code