如何获取js异步请求返回值

Love The Way You Lie 2022-05-31 12:55 422阅读 0赞

使用定时函数模拟异步请求

  • 回调函数

    1. function doSomething(callback){
    2. setTimeout(function(){
    3. console.log('执行结束');
    4. let result = 4;
    5. callback(result);
    6. },100);
    7. }
    8. function callback(result){
    9. console.log('接收到结果为:'+result);
    10. }
    11. doSomething(callback);
    12. //doSomething((result)=>{console.log('接收到结果为:'+result)});
  • 使用es6提供的Promise函数

    1. function doSomething(){
    2. return new Promise(function(resolve){
    3. setTimeout(function(){
    4. console.log('执行结束');
    5. let result = 6;
    6. resolve(result);
    7. },100);
    8. });
    9. }
    10. doSomething().then(result=>{
    11. console.log('接收到结果为:'+result);
    12. });
  • Generator函数

    1. function doSomething(){
    2. setTimeout(function(){
    3. let result = 6;
    4. it.next(result);
    5. },100);
    6. }
    7. function *gener(){
    8. var result = yield doSomething();
    9. console.log(result);
    10. }
    11. let it = gener();
    12. it.next();
  • 使用es7新特性async

    1. function doSomething(){
    2. return new Promise(resolve=>{
    3. setTimeout(function(){
    4. let result = 6;
    5. resolve(result);
    6. },100);
    7. });
    8. }
    9. async function action(){
    10. let result = await doSomething();
    11. console.log(result);
    12. }
    13. action();

发表评论

表情:
评论列表 (有 0 条评论,422人围观)

还没有评论,来说两句吧...

相关阅读

    相关 jq异步获取

    > 在开发过程中,如果使用jquery时,有时候会用到ajax的一些方法去异步获取值,这时候就是出现一些问题,如下: > > var arr = []; >