如何使用ArkTS 发起一个同步的请求,服务器有响应或出错才返回

如何使用ArkTS 发起一个同步的请求,服务器有响应或出错才返回

HarmonyOS
2024-05-30 22:45:53
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
失望的满天星
// Index.ets代码 
import taskpool from '@ohos.taskpool'; 
import http from '@ohos.net.http'; 
 
// 步骤1: 定义并发函数,内部调用同步方法 
@Concurrent 
function test(func: Function) { 
  func(); 
} 
 
function baidu() { 
  console.log('testTag: start') 
  //执行访问百度 
  let httpRequest = http.createHttp(); 
  let res = httpRequest.request('www.baidu.com'); 
  // 线程休眠2秒 
  let t: number = Date.now(); 
  while (Date.now() - t < 5000) { 
    continue; 
  } 
  console.log('testTag 线程休眠5秒'); 
  console.log('testTag: end ' + res); 
} 
 
// 步骤2: 创建任务并执行 
async function asyncGet(): Promise<void> { 
  // 创建task并传入函数func 
  let task: taskpool.Task = new taskpool.Task(test, baidu()); 
  // 执行task任务并对同步逻辑后的结果进行操作 
  console.info("testTag " + String(await taskpool.execute(task))); 
} 
 
@Entry 
@Component 
struct Index { 
  @State message: string = 'Hello World'; 
 
  build() { 
    Row() { 
      Column() { 
        Text(this.message) 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
          .onClick(async () => { 
            asyncGet() 
            console.log('testTag 同步请求执行完毕 线程继续工作') 
          }) 
      } 
      .width('100%') 
      .height('100%') 
    } 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.

参考链接:

同步任务开发指导

分享
微博
QQ
微信
回复
2024-05-31 21:53:01


相关问题
HarmonyOS HTTPS请求如何验证服务器证书
1364浏览 • 1回复 待解决
请求服务器图片资源刷新卡片
1361浏览 • 1回复 待解决
Web组件如何发起一个下载任务?
901浏览 • 1回复 待解决
鸿蒙系统类似苹果服务器吗?
9827浏览 • 1回复 待解决
服务器如何安装双centos系统?
2667浏览 • 1回复 待解决