zoukankan      html  css  js  c++  java
  • Node.js 同步与异步编程

    同步API: 只有当前API执行完成之后,才能继续执行下一行API。从上往下,一行一行的执行。

    console.log("one")
    
    console.log("two")

    异步API: 当前的API执行不会阻塞后续代码的执行。

     console.log("one")
    
    setTimeout ( () =>  console.log("two"), 3000)
    
    console.log("three")
    

    同步API与异步API的区别(获取返回值)

    同步API可以从返回值拿到API的执行结果,但是异步API不可以。

    // 同步
    
    function sum (a, b) {
      return a+ b  
    }
    
    // 异步
    
    function getMsg () {
      setTimeout( function () {
        console.log('hello node.js')  
      })   
    }
    

    异步API获取数据的方式(回调函数)

     1 function getMsg (fn) {
     2   setTimeout(function () {
     3     fn({
     4       msg: 'hello'
     5     })
     6   }, 3000)
     7 }
     8 
     9 getMsg(function (data) {
    10   console.log(data)
    11 })
  • 相关阅读:
    test20180922 倾斜的线
    test20180921 量子纠缠
    test20180921 手机信号
    test20180919 选择客栈
    BZOJ3083 遥远的国度
    test20180907 day1
    [ZJOI2010]基站选址
    HDU3584 Cube
    POJ2155 Matrix
    test20180902 day1
  • 原文地址:https://www.cnblogs.com/liea/p/11220711.html
Copyright © 2011-2022 走看看