使用promise封装方法

  使用promise封装方法优点很多,主要一大特定就是可以解决异步问题

//使用promise封装方法
export default function webSocket(data) {
    return new Promise((resolve, reject) => {
       //这里面可以写任意方法,或者是ajax请求,
       //我们只需要在需要返回结果的地方使用
        resolve(data)
        即可,data可以是任意类型,方便调用方获取结果
    });
}


//调用方法
webSocket(data)
 .then(response => {
       //成功后的回调,response就是前面传递来的参数
     })
   .catch(error => {
     //失败后的回调
  });

//简易使用(只考虑成功,不考虑失败)
webSocket(1).then( a=>{
     console.log(a)
})

例子:

  封装

export default function webSocket(data) {
    return new Promise((resolve, reject) => {
        // 创建 WebSocket 连接
        const socket = new WebSocket('ws://localhost:7000',[localStorage.getItem("token") || ""]);

        // 连接成功时触发
        socket.addEventListener('open', (event) => {
            console.log('WebSocket 连接成功!');
            console.log(data)
            // 向服务器发送消息
            socket.send(JSON.stringify(data));
        });

        // 接收到服务器发送的消息时触发
        socket.addEventListener('message', (event) => {
           // 服务器发送过来的消息event.data,是一个Blob 对象,需要将其转换才能被我们所使用
            // 将 Blob 对象转换为字符串
            event.data.arrayBuffer().then((buffer) => {
                const decoder = new TextDecoder();
                const data = decoder.decode(buffer);
                resolve(data);
            });
        });

        // 连接关闭时触发
        socket.addEventListener('close', (event) => {
            console.log('WebSocket 连接关闭!');
            reject('WebSocket 连接关闭!');
        });
    });
}

  调用

webSocket({data,file,nowApi:'add'})
                .then(response => {
                    // 上传成功后调用 onSuccess 回调函数
                    onSuccess!(response);
                    console.log(JSON.parse(response))
                })
                .catch(error => {
                    // 上传失败后调用 onError 回调函数
                    onError!(error);
                });

  websocket方法为异步方法,如果我们使用的是普通函数去封装他,那么调用后极有可能会拿不到返回结果。现在我们使用promise封装它,在他返回信息成功的时候调用resolve()方法,并将返回的数据传递给使用者。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值