async + await + promise
async + await + promise
以下写的是微信小程序的demo,可供参考,js使用方式一样的
await
函数返回的是promise
函数对象,async
结合await
使用,await
要等待的就是promise
,所以不能直接return wx.request等类似的异步函数。
使用的过程中,应该将异步请求的代码,包装到Promise对象中 返回参数: 需要两个参数 第一个是成功时回调,第二个是失败时回调,相当于return,只不过调用时机不一样。
function httpPost(url, data) {
var promise = new Promise((resolve, reject) => {
wx.request({
url: url,
data: data,
method: 'POST',
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {//服务器返回数据
resolve(res);
},
fail: function (e) {
reject('http error');
}
})
});
return promise;
}
// async+await一起使用
async function start(){
const word1 = await httpPost('1','')
console.log(word1)
const word2 = await httpPost('2','')
console.log(word2)
const word3 = await httpPost('3','')
console.log(word3)
// 或者
await httpPost('3','').then(res=>{ });
httpsLogin().then(res=>{
},err=> {
// 返回reject
console.log('err::',err)
});
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!