async,await综合示例

用户列表页提供两个接口,
一个接口返回所有用户的索引,
另外一个接口根据用户索引返回用户的姓名

服务器端

/**
 * Created by anchao on 17-7-6.
 */
const express = require('express');
const expressStatic = require('express-static');

const app = express();
app.listen(8080);

app.use('/person',(req,res)=>{
  res.send(JSON.stringify([0,1,2,3,4,5])).end();
});

app.use('/personinfo',(req,res)=>{
  let arr = ["tom","lucy","lili","ac","pvfhv","alex"];
  res.send(arr[req.query.id]).end();
});


app.use(expressStatic('./www/'))


客户端:

/**
 * Created by anchao on 17-7-6.
 */
//获得用户索引
function getPersonIndex () {
  return new Promise(function (resolve, reject) {
    $.get('/person').done(data=>{
      resolve(JSON.parse(data));
    })
  });
}


let getData = async function () {
  //用户索引数组
  let arr = await getPersonIndex();

  arr.forEach(id=>{
    let getName = async function () {
      let name = await _getInfo(id);
      $('#div1').append(name+',');
    }

    getName();
  });

  //根据用户的id获得用户姓名
  function _getInfo (id) {
    return new Promise(function (resolve, reject) {
      $.get('/personinfo',{id}).done(name=>{
        resolve(name);
      })
    })
  }
}

getData();

欢迎分享本文,转载请保留出处:前端ABC » async,await综合示例

赞 (2)
分享到:更多 ()

发表评论 0