promise封装

new Promise((resolve, reject) => {
    var param = 'Promise 执行完后返回的数据';
    var error = 'Promise 异步执行异常';
    if( error ) {
        reject(new Error('Promise 异步执行异常'));
    } else {
        resolve(param);
    }
}).then((res) => {
//  这里res就是Promise中的param参数
    console.log(res);  //  Promise 执行完后返回的数据
    var param = '第一个then 执行完后返回的数据';
    return param;
}).then((res) => {
//  这里的res就不是Promise中resolve的param参数了,而是上一个then中的返回值
    console.log(res);  //  第一个then 执行完后返回的数据
}).catch((error) => {
//  这里是Promise执行reject方法中的参数
    console.log(error); //  Promise 异步执行异常
});

function testAwait (x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}
 
async function helloAsync() {
  var x = await testAwait ("hello world");
  console.log(x); 
}
helloAsync ();

猜你喜欢

转载自blog.csdn.net/weixin_39418338/article/details/120013040