Promise 对象是由关键字 new 及其构造函数来创建的。构造函数会,把一个叫做“处理器函数”(executor function)的函数作为它的参数。这个“处理器函数”接受两个函数resolve 和 reject 作为其参数。当异步任务顺利完成且返回结果值时,会调用 resolve 函数,而当异步任务失败且返回失败原因(通常是一个错误对象)时,会调用reject 函数。
var promise1 = new Promise(function(resolve, reject) { setTimeout(function() { resolve('foo'); }, 300); }); promise1.then(function(value) { console.log(value); // foo }); console.log(promise1); // [object Promise]
Promise.prototype.then(onFulfilled, onRejected);
onFulfilled将接收一个参数,参数值由当前Promise实例内部的resolve()方法传值决定;onRejected将接收一个参数,参数值由当前Promise实例内部的reject()方法传值决定。
const p = function(){ let num = Math.random(); return new Promise((resolve, reject) => { setTimeout(() => { num > 0.5 ? resolve(num) : reject(num); }, 1000); }) }; p().then(val => { console.info(`Status switches to fulfilled, and the value is ${val}`); }, val => { console.info(`Status switches to reject, and the value is ${val}`); })
上面的例子中。若随机数大于0.5,Promise实例状态将转变成fulfilled,则then方法将调用第一个传入的回调函数;Promise实例状态将转变成reject,则then方法将调用第二个传入的回调函数;
const p = function(){ return new Promise((resolve, reject) => { setTimeout(() => { reject('Refused the request!'); },0); }) }; const p2 = function(){ return new Promise((resolve, reject) => { setTimeout(() => { resolve(p()) },0); }) }; p2().then(val => { console.info('Status switches to fulfilled'); console.info(val); }, val => { console.info('Status switches to reject'); console.info(val); }); // 输出 "Status switches to reject" // 输出 "Refused the request!"
上面的例子中:当Promise实例内部的fulfilled(或reject)传入的是Promise实例时,其状态以及then()方法的传值将由传入的Promise实例的状态决定。
先从字面意思来理解,async 是“异步”的意思,而 await 是等待的意思。所以应该很好理解 async 用于申明一个 异步的function(实际上是async function 对象),而 await 用于等待一个异步任务执行完成的的结果。并且 await 只能出现在 async 函数中。
async function testAsync() { return "hello async"; } const data = testAsync(); console.log(data);
// async async function testAsync() { return "hello async"; } let data = testAsync().then( (data) => { console.log(data) // hello async return data }); console.log(data);
function say() { return new Promise(function(resolve, reject) { setTimeout(function() { let age = 26 resolve(`hello, joel。今年我 ${age} 岁`); }, 1000); }); } async function demo() { const v = await say(); // 输出:hello, joel。今年我 26 岁 等待这个say 的异步,如果成功把回调 resole 函数的参数作为结果 console.log(v); } demo();
function say() { return new Promise(function(resolve, reject) { setTimeout(function() { let age = 26 reject(`hello, joel,发生了异常。今年我 ${age} 岁`); }, 1000); }); } async function demo() { try { const v = await say(); // 输出:hello, joel,发生了异常。今年我 26 岁 等待这个say 的异步,如果成功把回调 resole 函数的参数作为结果 console.log(v); } catch (e) { console.log(e) } } demo();
https://www.cnblogs.com/CandyManPing/p/9384104.html