美文网首页
JS回调函数、异步、Generator、async-await

JS回调函数、异步、Generator、async-await

作者: wyc0859 | 来源:发表于2019-04-21 12:58 被阅读0次

回调函数

 save() {
    this.test(res=>{
      console.log('save:',res)
    }) 
  },
  test(callback){
    var x=1+1
    callback(x)
    console.log('test:', x);
    callback(x)
  }

结果为:
save: 2
test: 2
save: 2

简单的异步理解

下面代码可以看出,结果先显示1,2,

function a(){
console.log(1)
setInterval(function (args) {
        console.log('interval')
    }, 1000);
console.log(2)
}

a()  //结果为1  2 interval interval interval

如何理解JS异步执行机制

JS是单线程程序,从而避免了并发访问的一系列问题。但也正是由于单线程这样一个机制,导致JS的异步执行并不能按照传统的多线程方式进行异步执行,所有的异步时间要插入到同一个队列中,依次在主线程中执行。

promise对象有then属性
resolve成功执行,reject失败执行。
then可以进行链式操作,then有2个函数参数,第二个表示失败后调用,但一般在then后接.catch来捕获异;如果用then的两个参数,就会出现分支,影响阅读。

Promise与callback的区别

Promise只是对于异步操作代码可读性的一种变化,它并没有改变 JS 异步执行的本质,也没有改变 JS 中存在callback的现象。

Generator和async-await的对比

// 定义 Generator 函数
function* Hello() {
    yield 100
    yield (function () {return 200})()
    return 300
}

var h = Hello()
console.log(typeof h)  // object

console.log(h.next())  // { value: 100, done: false }
console.log(h.next())  // { value: 200, done: false }
console.log(h.next())  // { value: 300, done: true }
console.log(h.next())  // { value: undefined, done: true }
const readFilePromise = Q.denodeify(fs.readFile)
// 定义 async 函数
const readFileAsync = async function () {
    const f1 = await readFilePromise('data1.json')
    const f2 = await readFilePromise('data2.json')
    console.log('data1.json', f1.toString())
    console.log('data2.json', f2.toString())
    return 'done' 
}
// 执行
const result = readFileAsync()

可以看到async function代替了function*,await代替了yield,使用async-await时候不用再引用co这种第三方库了,直接执行即可,其他的再没有什么区别。

async/await比Promise强在哪儿

function sayHi(name) {
  return new Promise((resolved, rejected) => {
    setTimeout(() => {
      resolved(name);
    }, 2000)
  })
}

async function sayHi_async(name) {
  const sayHi_1 = await sayHi(name)
  console.log(`你好, ${sayHi_1}`)
  const sayHi_2 = await sayHi('李四')
  console.log(`你好, ${sayHi_2}`)
  const sayHi_3 = await sayHi('王二麻子')
  console.log(`你好, ${sayHi_3}`)
}

sayHi_async('张三')
// 你好, 张三
// 你好, 李四
// 你好, 王二麻子

与之前长长的then链和then方法里的回调函数相比,这样的写法看起来像是同步写法并且更加清爽,更加符合编程习惯。

async buy_price() {             
            const is_vip = await this.check_invite(sfm)
            const price = await this.get_vip_price() 
            if(is_vip){
                this.vip_price=price[0]
            }else{
                this.vip_price=price[1]
            }   
},    
check_invite(sfm){
    return this.$api.http.post('check',{code}).then(res=>{
        return res;
    });
},
get_vip_price(){
    return this.$api.http.get('select_vip').then(res=>{
        return res;                             
    })
}

相关文章

  • JS回调函数、异步、Generator、async-await

    回调函数 结果为:save: 2test: 2save: 2 简单的异步理解 下面代码可以看出,结果先显示1,2,...

  • Generator

    异步编程解决方案 Generator 函数、Promise 、回调函数、事件 Generator 函数有多种理解角...

  • JS中的异步操作

    JS中异步编程的方法有: 回调函数 事件监听 发布/订阅 promise generator(ES6) async...

  • Async/Await 函数用法

    JavaScript编程异步操作解决方案:回调函数 => Promise对象 => Generator函数 => ...

  • 07_Node.js Event

    一、回调函数 callback 1、回调函数 Node.js 异步编程的直接体现就是回调,异步编程依托于回调来实现...

  • 17Generator函数的异步应用

    传统异步 回调函数 响应事件 发布/订阅 Promise Generator 异步案例 适用场景,执行a任务,暂停...

  • CO

    拥抱Generator,告别异步回调

  • node.js(六)

    Node.js 回调函数Node.js 异步编程的直接体现就是回调。异步编程依托于回调来实现,但不能说使用了回调后...

  • 01node.js

    01、模块 02、关注学习 03、Node.js 回调函数Node.js 异步编程的直接体现就是回调。异步编程依托...

  • 2020-02-23

    Node.js回调函数 Node.js异步编程的直接体现就是回调 异步编程依托于回调来实现,但不能说使用了回调后程...

网友评论

      本文标题:JS回调函数、异步、Generator、async-await

      本文链接:https://www.haomeiwen.com/subject/arndgqtx.html