JavaScriptWhat you need to knowPromiseDetailed knowledge

1. How to implement onesleepFunction (delay function)

This is easily implemented with promises and setTimeout

/** * delay function *@param {Number} Time time * /
function sleep (time = 1500) {
    return new Promise((resolve) = > {
        setTimeout(() = > {
            resolve(true)
        }, time)
    })
}
Copy the code

2,promiseConstructor,thenMethods,catchMethods,finallyWhich methods are asynchronous and which are synchronous?

The Promise constructor is executed synchronously, and the THEN, catch, and finally methods are executed asynchronously.

3. How to cancel onepromise?

Cancel a Promise

1. Usepromise.race()

  • Promise.race(iterable)

When any child promise in the Iterable argument succeeds or fails, the parent promise immediately calls the parent promise’s binding handle using the child promise’s success return value or failure details as arguments and returns the promise object.

/ * * *@author guoqiankunmiss* /
// Encapsulate a function that cancels promises, using the promise.race feature
function stopPromise (stopP) {
	let proObj = {};
	let promise = new Promise((resolve, reject) = > {
		proObj.resolve = resolve;
		proObj.reject = reject;
	})
	proObj.promise = Promise.race([stopP, promise])
	return proObj
}
// A promise for the.then method to be executed 5 seconds later
let promise = new Promise((resolve, reject) = > {
    setTimeout(() = > {
        resolve(123);
    }, 5000);
});
// Call the function
let obj = stopPromise(promise);
// Collect return values
obj.promise.then(res= > {
    console.log(res);
});
// Cancel the Promise operation after two seconds
setTimeout(() = > {
	obj.resolve("The Promise request has been cancelled!");
}, 2000)
Copy the code

More than 4,promiseHow to get the first successpromise?

Get the first successful Promise of multiple promises

1. Promise.allTo improve the

Make use of the promise.all feature, traverse the promise array, judge according to the return value, if successful, to reject return, if failed to resolve continue execution.

// The first successful Promise
function firstProSuccess (allProMise) {
  If the promise array succeeds, reject is returned. If the promise array fails, resolve is returned.
  return Promise.all(allProMise.map(item= > {
    return item.then(
      res= > Promise.reject(res),
      err= > Promise.resolve(err)
    )
  })).then(
    errors= > Promise.reject(errors),
    val= > Promise.resolve(val)
  )
}
Copy the code

2. Promise.any

  • Promise.any(iterable)

Receives a collection of Promise objects, and when one Promise succeeds, returns the value of that successful Promise.

Disadvantages: Compatibility issues

More than 5,promiseAnd all thepromiseReturns the result (returns the value regardless of success/failure)

1. Promise.allTo improve the

This is similar to the previous principle, except that there is no action when successful, and resolve when successful

2. Promise.allSettled()

  • Promise.allSettled(iterable)

Return a promise after all the given promise has fulfilled or Rejected.

Disadvantages: Compatibility issues

6, tell me aboutpromiseWhat are the static methods of?

1. Promise.all(iterable)

Receives a Promise array object (an iterable Promise instance object) and, on success, returns an array of all promises; When one of them fails, the current failed Promise object is returned.

2. Promise.allSettled(iterable)

Receives a Promise array object and returns a new set of Promise arrays when all is done (success/failure)

3. Promise.any(iterable)

Receives an array of Promise objects, and returns a successful promise value when any of them succeed

4. Promise.race(iterable)

Receives an array of Promise objects and returns the promise value when either one succeeds or fails

5. Promise.reject(reason)

Return a Promise object in a failed state.

6. Promise.resolve(value)

Returns a Promise object whose state is determined by the given value.

7. Promise.finally(onFinally)

This will be called after the current promise is fulfilled, no matter the state of the promise is fulfilled or failed.

8. Promise.try(f)

Take a function and return a promise.

It provides a uniform processing mechanism for all operations, so if you want to manage processes with then methods, it’s best to wrap them all in promise.try.

  • Better error handling
  • Better interoperability
  • Easy to navigate

Promise-try

7,Promise.thenDo you understand the second parameter of? and.catchWhat’s the difference?

The then() method returns a Promise.

It needs at most two arguments: a callback to Promise’s success and failure cases.

p.then(onFulfilled[, onRejected]);
p.then(value= > {
  // fulfillment
}, reason= > {
  // rejection
});
Copy the code

The second argument is also a function that is a callback to the failure case.

thenSecond parameter catch
thenMethod parameters PromiseInstance method of
thenThe first argument to throw an exception is not caught The first argument to then throws an exception that can be caught
It’s a function Nature isthenMethod syntax sugar
If the second argument is equal tocatchCoexisting,promiseInternal error, second parameter can be captured At this point,catchThe second parameter does not exist.catchTo capture it
Not recommended It is recommended to usecatchError capture

Eight,Promise.resolveHow many cases are there?

1. The parameter is onePromiseThe instance

If the argument is a Promise instance, promise.resolve will return the instance unchanged.

2. The parameter is onethenableobject

The promise.resolve () method turns this object into a Promise object and immediately executes the thenable object’s then() method.

3. The parameter does not existthen()Method object, or not object at all

If the parameter is a raw value, or an object that does not have a then() method, the promise.resolve () method returns a new Promise object with the state Resolved.

4. No parameters

Return an Resolved Promise object directly.

9, if.thenWhat if the arguments in the.

Promise.resolve(1)
    .then(2)
    .then(console.log)
/ / 1
Copy the code

If the argument in.then is not a function, it is internally replaced with (x) => x, the function that returns the final result of the promise as is.

10, if.finallyFollowed by another.thenSo thisthenWhat are the values inside?

Promise.resolve('resolve')
  .finally(() = > {
    console.log('this is finally')
    return 'finally value'
  })
  .then(res= > {
    console.log(The then function after 'finally 'has the value res:', res)
  })
// this is finally
Copy the code

The then function after finally, res, has the value: resolve

  1. finallyDoes not accept any arguments in the callback function of
  2. inpromiseAt the end of the day, whatever the result isfulfilledOr is itrejected, will be implementedfinallyCallback function;
  3. finallyThe return is a previous onePromiseObject value.

11,.all.raceDo other asynchronous tasks continue when the first exception is thrown in the passed array?

Yes, it will continue, just not in then/catch.

When the browser executes the following code, you can see that console continues to execute when an error is reported, but it is not shown in the corresponding callback function.

function sleep (n) {
    return new Promise((resolve, reject) = > {
        console.log(n)
        Math.random() > 0.5 ? reject(n) : resolve(n)
    }, n % 2= = =0 ? 1000 * n : 1000)}Promise.all([sleep(1), sleep(2), sleep(3)])
  .then(res= > console.log('all res: ', res))
  .catch(err= > console.log('all err:', err))
Promise.race([sleep(1), sleep(2), sleep(3)])
  .then(res= > console.log('race res: ', res))
  .catch(err= > console.log('race err:', err))
Copy the code

12,.allIs it concurrent or serial?

Is concurrent, but returns values in the same order as the array received in promise.all.

13,promiseWhy can you make chain calls

Because the then, catch, and finally methods return a new promise, we are allowed to make chain calls.

14,async/await

1. Implementation principle

Async function is implemented based on generator, so it involves knowledge about generator. In the absence of async functions, the CO library is usually used to execute the generator, so we can emulate async implementation with CO.

2. Simple implementation

1)co
function Asyncfn() {
  return co(function* () {
    / /...
  });
}
function co(gen) {
  return new Promise((resolve, reject) = > {
    const fn = gen();
    function next(data) {
      let { value, done } = fn.next(data);
      if (done) return resolve(value);
      Promise.resolve(value).then(res= > {
        next(res);
      }, reject);
    }
    next();
  });
}
Copy the code
2)GeneratorFunctions and self-effectors
function spawn(genF) {
    return new Promise(function(resolve, reject) {
        const gen = genF();
        function step(nextF) {
            let next;
            try {
                next = nextF();
            } catch (e) {
                return reject(e);
            }
            if (next.done) {
                return resolve(next.value);
            }
            Promise.resolve(next.value).then(
                function(v) {
                    step(function() {
                        return gen.next(v);
                    });
                },
                function(e) {
                    step(function() {
                        returngen.throw(e); }); }); } step(function() {
            return gen.next(undefined);
        });
    });
}
Copy the code