1. What is Promise and related requirements

  • Promise is a new built-in class for ES6 (New Promise)
  • Promise is a “Promise” design pattern designed to address the “callback hell” problem of ASYNCHRONOUS JS programming.
  • Promises are used to control asynchronous programming. New Promises themselves are not asynchronous and execute executor functions immediately (although we often control an asynchronous operation in executor).
    1. Resolve/reject: Arguments passed to executor functions (parameter values are functions)
    2. The initial state of a promise is pending and its initial value is undefined
    3. Resolve ([value]) : Change the state of promise to a fulfilled/resolved state and change its value to [value]
    4. Reject ([reason]) : Reject ([reason]) : Change the state of the promise to Rejected and change its value to [reason]
  • Once the state changes, it can’t change to any other state
  • If an executor function fails, the state will also fail, and changing its value is the cause of the failure
  • Asynchrony in a Promise refers to resolve/reject execution for the following reasons:
    1. Both methods are executed not only to change the state and value, but also to inform the execution of one of the two callback functions stored by THEN
    2. When you execute two methods, you wait for a promise to store the method based on then and then execute it
new Promise() :TypeError: Promise resolver undefined is not a function
new Promise([executor]) :executorIs an executable function - [[PromiseStatus]] PromiseStatus:pending,fulfilled,rejected
 - [[PromiseValue]]  PromiseValue of [prototype] -then
 - catch
 - finallyCommon Object -reject
 - resolve
 - all
 - race
Copy the code
  • Then registers a successful or failed callback function, which returns a new Promise instance
    1. The state and value of the instance returned by new Promise([executor]) are determined by the resolve/reject execution, or by whether the [executor] function execution reported an error
    2. .then(…) Value => If a method is executed successfully and an error is reported, the value returned by the method is the value of the new instance. If a method is executed successfully, the value returned by the method is the value of the new instance. Special: If a new Promise instance is returned, the state and value of the current instance determine the state and value of P2
    let p1 = new Promise((sesolve, reject) = > {
        resolve('OK')})let p2 = p1.then(value= >{
        console.log('Executed successfully', value)
    }, reason= > {
        console.log('Failed to execute', reason)
    })
    p2.then(value= >{
        console.log('Execute 2 successfully', value)
    }, reason= > {
        console.log('Failed to execute 2', reason)
    })
    
    Copy the code

Second, then

  1. Store two callback functions based on then:
  • The state is successfully invoked for the first callback function, and the parameter value is [[PromiseValue]]
  • The second callback is invoked with a failed state
let p = new Promise(resolve, reject) {
    resolve('OK')
    reject('NO')
}
p.then((value) = >{
    console.log('Successfully executed function', value)
}, () = >{
    console.log('Failed function execution', value)
})
Copy the code

Then ([fnOK], [fnNo]).then([fnOK]).then(null, [fnNo]).then().then() But this method is not registered, then the continuation (find the corresponding method registered in the next THEN).

Promise.reject(100)
    .then(value= >{
        console.log('OK', value);
    }/*,reason=>{ return Promise.reject(reason); } * /)
    .then(null/*value=>{ return Promise.resolve(value); } * /.reason= >{
        console.log('NO', reason); //NO,100
        return Promise resolve(200);
    })
    .then(null.reason= >{
        console.log('NO', reason);
    })
    .then(value= >{
        console.log('OK', value); //OK,200
    })
Copy the code

(reason=>{}) ===. Then (null, reason=>{})

Promise.reject(100).then(value= >{
    console.log('OK', value);
}).catch(reason= >{
    console.log('NO', reason);
})
Copy the code

All/race => return a new Promise instance

All: Waits for all Promise instances to be successful and all return instances to be successful. (If all Promise instances are successful, all return instances are successful. If one Promise instance fails, all return instances are failures.) race: Waits for the latest Promise instance to return results

function fn1() {
    return Promise.resolve(1)}function fn2() {
    return new Promise(resolve, reject) => {
        setTimeout(() = >{
            resolve(2)},2000)}}function fn3() {
    return new Promise(resolve, reject) => {
        setTimeout(() = >{
            resolve(3)},1000)}}//all: the instance returned as a whole is successful
Promise.all([fn1(),fn2(),fn3()]).then(values= >{
    //values[Array]: Stores the results returned by each instance in order
    console.log(values);
}).catch(reason= >{
    // If an instance fails, the whole instance fails
    console.log('NO', reason);
})

//race: whichever comes first
Promise.race([fn1(),fn2(),fn3()]).then(value= >{
    console.log('OK',value);
}).catch(reason= >{
    console.log('NO', reason);
})
Copy the code

4. Interview question: Design a wait function, wait N time to do things

function delay( callback,interval = 1000){
    return new Promise( resolve= >{
        let timer = setTimeout(() = >{
            clearTimeout(timer);
            timer = null;
            resolve();
        },interval);
    });
}

/ / the first
delay(1000).then(() = >{
    console.log(1);
    return delay(2000);
}).then(() = >{
    console.log(2);
    return delay(3000);
}).then(() = >{
    console.log(3);
})

/ / the second
(async function(){
    await delay(1000);
    console.log(1);
  
    await delay(2000);
    console.log(2);
  
    await delay(3000);
    console.log(3); }) ();Copy the code

Async, await

Provided in ES7, it is a complement to promises (promise syntactic sugar). Async decorates a function that returns the result as a Promise instance

  • State: Most are successful, and if code execution fails, returns a failure, or manually returns a new Promise instance, the state of the new instance is handled

Use await to change an asynchronous task into something similar to synchronization (not synchronous, asynchronous in nature, but a microtask in asynchrony)

function fn2() {
    return new Promise(resolve, reject) => {
        setTimeout(() = >{
            resolve(2)},2000)}}function fn3() {
    return new Promise(resolve, reject) => {
        setTimeout(() = >{
            resolve(3)},1000)}} (async function(){
    To await a method, we must base the method on the async modifier
    /* 1. Execute fn2 first and see if fn2 returns a promise of success or failure. Asynchronous: It will treat the whole code under the current context and await as an asynchronous microtask and place it in the waiting EventQueue. 3. Await only if the promise instance is in the success state, if the return state is in the success state, value will get [[PromiseValue]], 4. 'await' the function immediately. Even if the function returns success or failure status immediately, 'await' the function immediately
    let value = await fn2();
    console.log(value)
})();
console.log(1)
Copy the code

6. Micro task and macro task exercises

async function async1 (){
    console.log('async1 start');
    await async2();
    console.log('async1 end');
}
async function async2() {
    console.log('async2');
}
console.log('script start');
setTimeout(function(){
    console.log('setTimeout')},0)
async1();
new Promise(function(resolve){
    console.log('promise1');
    resolve();
}).then(function(){
    console.log('promise2');
});
console.log('script end');
Copy the code