异步、同步
含义
异步:调用方不会立即得到结果,而是在调用发出后调用者可用继续执行后续操作,被调用者通过状体来通知调用者,或者通过回掉函数来处理这个调用
同步:调用方得等待这个调用返回结果才能继续往后执行
同步使用
let addEditStr = '' // 调用完ajax请求之后 即可用addEditStr function selectContent($element) { $.ajax({ url: "请求路径", data: JSON.stringify({ 'list': { 'key': 'value' } }), type: "post", dataType: 'json', async: false, // 同步 contentType: "application/json", success: function (resultdata) { if (resultdata.code == 0) { // 请求成功之后对addEditStr进行处理 return addEditStr = resultdata } else { errorShow(res); } }, error: function () { console.info('请求错误') } }) }
异步使用
async loadQuote () { try { const response = await axios.get('https://api.kanye.rest/').then(response => { console.info('3333333333333333333333') return response }) this.quote = response.data.quote console.info('222222222222222222') } catch (err) { console.log(err) } }, async loadQuote2 () { console.info('1111111111111') },
输出:11111111 3333333 222222
异步表示很多事情在一起并行的处理,因此俩异步函数之间先输出111111
函数内部含有await,等待请求结果,因此先输出33333,后输出2222222

浙公网安备 33010602011771号