• 24小时服务热线:400-088-1128

当前位置 南顺网络>> 知识拓展

详解 js promise

Promise是一个构造函数。

该函数有一个函数参数。

函数参数有两个参数 resolve reject ,分别为成功与失败之后的回调函数。

1.Promise.all()=>用于汇总多个promise的结果。

2.Promise.race()

3.Promise.reject(reason)

4.Promise.resolve(value)

5.Promise.prototype.catch(onRejected)

6.Promise.prototype.then(onFulfilled, onRejected)

7.Promise.prototype.finally(onFinally)


async

1.一个async函数可以包含一个await表达式,暂停异步函数的执行并等待传入Promise的解析,然后恢复async函数的执行并返回解析后的值。

eg:

function resolveAfter2Seconds(x) {

  return new Promise(resolve => {

    setTimeout(() => {

      resolve(x);

    }, 2000);

  });

}

async function add1(x) {

  const a = await resolveAfter2Seconds(20);

  const b = await resolveAfter2Seconds(30);

  return x + a + b;

}

add1(10).then(v => {

  console.log(v);  // prints 60 after 4 seconds.

});

async function add2(x) {

  const p_a = resolveAfter2Seconds(20);

  const p_b = resolveAfter2Seconds(30);

  return x + await p_a + await p_b;

}

add2(10).then(v => {

  console.log(v);  // prints 60 after 2 seconds.

});

2.函数重写承诺链

function getProcessedData(url) {

  return downloadData(url) // returns a promise

    .catch(e => {

      return downloadFallbackData(url)  // returns a promise

    })

    .then(v => {

      return processDataInWorker(v); // returns a promise

    });

}

它可以用一个async函数重写,如下所示:

async function getProcessedData(url) {

  let v;

  try {

    v = await downloadData(url); 

  } catch(e) {

    v = await downloadFallbackData(url);

  }

  return processDataInWorker(v);

}

Promise.all()

用法:Promise.all(迭代)
迭代:一个可迭代的对象,如Array或者String.

返回值
异步性

1.同步,当且仅当通过的迭代是空的时,Promise.all同步解析
2.异步,不然就要异步处理
  快速性
3.快速行为,如果任何元素被拒绝,则Promise.all被拒绝。

eg:

var p = Promise.all([]); // will be immediately resolved

var p2 = Promise.all([1337, "hi"]); // non-promise values will be ignored, but the evaluation will be done asynchronously

console.log(p);

console.log(p2)

setTimeout(function(){

    console.log('the stack is now empty');

    console.log(p2);

});

// logs

// Promise { : "fulfilled", : Array[0] }

// Promise { : "pending" }

// the stack is now empty

// Promise { : "fulfilled", : Array[2] }

eg:

var p1 = new Promise((resolve, reject) => { 

  setTimeout(resolve, 1000, 'one'); 

}); 

var p2 = new Promise((resolve, reject) => { 

  setTimeout(resolve, 2000, 'two'); 

});

var p3 = new Promise((resolve, reject) => {

  setTimeout(resolve, 3000, 'three');

});

var p4 = new Promise((resolve, reject) => {

  setTimeout(resolve, 4000, 'four');

});

var p5 = new Promise((resolve, reject) => {

  reject('reject');

});

Promise.all([p1, p2, p3, p4, p5]).then(values => { 

  console.log(values);

}, reason => {

  console.log(reason)

});

//From console:

//"reject"

//You can also use .catch

Promise.all([p1, p2, p3, p4, p5]).then(values => { 

  console.log(values);

}).catch(reason => { 

  console.log(reason)

});

//From console: 

//"reject"

Promise.race()

用法 Promise.race(迭代)
1.如果通过的迭代是空的,则返回的promise将永远等待。

2.如果迭代包含一个或多个非承诺值和/或已经解决/拒绝的承诺,Promise.race 则将解析为在迭代中找到的这些值中的第一个。

3.也有异步性

eg:

var foreverPendingPromise = Promise.race([]);

var alreadyResolvedProm = Promise.resolve(666);

var arr = [foreverPendingPromise, alreadyResolvedProm, "non-Promise value"];

var arr2 = [foreverPendingPromise, "non-Promise value", Promise.resolve(666)];

var p = Promise.race(arr);

var p2 = Promise.race(arr2);

console.log(p);

console.log(p2);

setTimeout(function(){

    console.log('the stack is now empty');

    console.log(p);

    console.log(p2);

});// logs, in order:

// Promise { : "pending" } 

// Promise { : "pending" } 

// the stack is now empty

// Promise { : "fulfilled", : 666 }

// Promise { : "fulfilled", : "non-Promise value" }

var p1 = new Promise(function(resolve, reject) { 

    setTimeout(resolve, 500, 'one'); 

});

var p2 = new Promise(function(resolve, reject) { 

    setTimeout(resolve, 100, 'two'); 

});

Promise.race([p1, p2]).then(function(value) {

  console.log(value); // "two"

  // Both resolve, but p2 is faster

});

————————————————

版权声明:本文为CSDN博主「jeft_hai」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/jeft_hai/article/details/83243947