异步操作_异步和同步

异步操作_异步和同步1、Promise对象 promise异步操作有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败) promise对象只有从pending变为fulfilled和从pending变为rejected的状态改变。只要处于fulfilled和rejected时,

异步操作_异步和同步

1、Promise对象

promise异步操作有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)

promise对象只有从pending变为fulfilled和从pending变为rejected的状态改变。只要处于fulfilled和rejected时,状态就不会再变了即resolveed(已定型)

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

  resolve(‘sucess1’);

  resolve(‘sucess2’);

});

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

  resolve(‘sucess3’);

  reject(‘reject’);

})

p1.then(function(value) {

  console.log(value) ;

})

p2.then(function(value) {

  console.log(value);

})

缺点:

1、无法取消promise,一旦新建它就会立即执行,无法中途取消

2、如果不设置回调函数,promise内部抛出的错误,不会反应到外部

3、当处于pending状态时,无法得知目前进展到哪一个阶段

then方法

then方法接收两个函数作为参数,第一个参数是promise执行时的回调,第二个参数是promise执行失败时的回调,两个函数只会有一个被调用

特点:

1、在javascript事件队列中的当前运行完成之前,回调函数永远不会被调用

const p = new Promise((resolve, reject) => {

  resolve(‘sucess’);

})

p.then((value) => {

  console.log(value)

})

console.log(‘first’)

//first

//success

这时会先执行这个队列中的方法,然后再去执行then中的回调方法

2、.then形式添加的回调函数,不论什么时候,都会被调用

var Bool isSuccess = true

const p = new Promise((resolve, reject) => {

  if(isSuccess)resolve(‘sucess’);

  else reject(‘failture’)

}).then((value) => {console.log(value)},

    (error) => {console.log(error)}

)

典型的应用:封装ajax请求

const ajax = (options: requestConfig): Promise<any> => {

  if(!option.url || typeof options.url !== ‘string’) {

    throw new Error(‘url必传且只能为string类型’)

  }

  if (options.method && typeof method !== ‘string’) {

    throw new TypeError(‘method必须是string类型’)
  }
  const defaultOptions = {
    method: ‘GET’,
    header:   {
      ’X-Requested-With’: ‘XMLHttpRequest’,
      ’X-jd-ajax’: ‘1.0’
      ’X-jd-ts’: new Date().getTime()
    },
    isAuth: false,
    isLoading: false,
    fail() {
      Taro.hideLoading()
    }
  }
  const finalOptions = Object.assgin({},defaultOptions,options)
  finalOptions.url = `${ SERVER_URL }${ options.url }`
// @ts-ignore

  Taro.cleanInterceptors()
  Taro.addInterceptor(Interceptor.common)
  return Taro.request(finalOptions)

}

二、Generator函数

与普通函数的区别:

1、在function后面,函数名前面有个*

2、函数内部有yield表达式

其中*用来表示函数为Generator函数,yield用来定义函数内部的状态

function * func() {

  console.log(‘one’);

  yield ‘1’

  console.log(‘two’)

  yield ‘2’

  console.log(‘three’)

  return ‘3’

}

var f = func()

f.next() 

//one

 

//{value: “1”, done: false}

f.next()

//two

//{value: “2”, done: false}

f.next()

//three

//{value: “3”, done: true}

next方法带参和不带参

function* sendParameter() {

  console.log(”start)

  var x = yield ‘2’

  console.log(‘one:’ + x)

  var y = yield ‘3’

  console.log(‘two:’ + y)

  console.log(‘total is : ${x+y}’)

}

var sendp = sendParameter()

sendp.next(10)

//start

//{value: ‘2’, done:  false}

sendp.next(20)

//one: 20

//{value: “3”, done: false}

sendp.next(30)

//two:30

//total:50

//{value:undefined, done: true}

//用途:为不具备iterator接口的对象提供遍历方法

function* objectEntries(obj) {

  const propKeys = Reflect.ownKeys(obj);

  for(const propKey of propKeys) {

    yield [propKey, obj[prop]]

  }

}

const jane = {first: ‘Jane’, last: ‘Doe’}

for(const [key, value] of objectEntries(jane)) {

  console.log(‘${key}: ${value}’)

}

其中Reflect.ownKeys()返回对象所有的属性,不管属性是否枚举,包括symbol

jane原生是不具备iterator接口无法通过for…of遍历,这边用了Generator函数加上了iterator接口,所以就可以遍历jane接口了

三、async

1、async函数返回的是一个promise对象,可以使用then方法添加回调函数

async function helloAsync() {

  return ‘helloAsync’

}

console.log(helloAsync())  //Promise{<resolved>: ‘HelloAsync’}

helloAsync().then(v=>{

  console.log(v)           //helloAsync

})

2、async函数中可能会有await表达式,async函数执行时,如果遇到await就会先暂停执行,等到触发的异步操作完成后,恢复async函数的执行并返回解析值

await关键字仅在async function中有效

function testAwait() {

  return new Promise((resolve) => {

    setTimeout(function(){

      console.log(‘testAwait!’)

      resolve()

    },1000)

  })

}

async function helloAsync()  {

  await testAwait()

  console.log(‘helloAsync’)

}

helloAsync()

//testAwait

//helloAsync

await

1、await操作符用于等待一个promise对象,它只能在异步函数async function内部使用

2、返回值:返回promise对象的处理结果,如果等待的不是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()

//helloworld

3、正常情况下,await命令后面是一个promise对象,它也可以跟其他值,如字符串、布尔值、数值以及普通函数

function testAwait() {

  console.log(‘testAwait’)

}

async function helloAsync()  {

  await testAwait()

  console.log(‘helloAsync’)

}

helloAsync()

今天的文章异步操作_异步和同步分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/48185.html

(0)
编程小号编程小号
上一篇 2023-09-04
下一篇 2023-09-04

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注