云函数:test.js(xxx是我的网站,不方便写出,已经测试过是可用的,可以返回数据,但是写入云函数后结果是null)
// 云函数入口文件 const cloud = require( 'wx-server-sdk' ) cloud.init() exports.main = async (event, context) => { var request = require( 'request' ); var that = this request ({ url: 'xxx' , data: '' , header: {}, method: 'GET' , dataType: 'json' , responseType: 'text' , success: res => { return res.data }, fail: res => { }, complete: res => { }, }) } |
index.js
testFunction() { wx.cloud.callFunction({ name: 'test' , data: { }, success: res => { wx.showToast({ title: '调用成功' , }) console.log(res) }, fail: err => { wx.showToast({ icon: 'none' , title: '调用失败' , }) console.error( '[云函数] A 调用失败:' , err) } }) } |
本人新手,还很多东西不懂
请问各位高人,应该如何修改,才能得到result?
// 云函数入口函数 exports.main = async (event, context) => { const wxContext = cloud.getWXContext() const db = cloud.database() const _ = db.command const $ = db.command.aggregate /** * customers表和record表作连接 * @see https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/functions/async.html * 需要异步返回数据,否则返回的数据为null */ console.log('调用云函数查询设备信息(ID列表):' + event.deviceId) return new Promise((resolve , reject) => { db.collection('customers') .aggregate() .match({ _id:_.in(event.deviceId) }) .lookup({ from:'record', let:{ customersId:'$_id' }, pipeline:$.pipeline() .match(_.expr($.eq(['$uid','$$customersId']))) .sort({ record_time:-1 }) .limit(12) .done(), as: 'recordList' }) .end() .then(res => { console.log("返回结果列表:") console.log(res.list) // 通过resolve()返回结果 resolve(res) }) .catch(err => reject(err)) }) } //调用端 wx.cloud.callFunction({ name:'getDeviceInfo', data:{ 'deviceId':deviceId }, success:function(res){ wx.showToast({ title: '更新成功', icon:'success', }) console.log(res) }, faile:function(res){ } })
@see https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/functions/async.html
上一下我自己的写法,可能有点绕了
const cloud = require('wx-server-sdk')
cloud.init()
exports.main = async (event, context) => {
var request = require('request');
var that = this;
async function wait(x) {
return new Promise((resolve,reject)=>{
setTimeout(()=>{resolve(x)},3000)
})
}
var result = request({
url: 'xxx',
data: {},
header: {},
method: 'POST',
dataType: 'json',
responseType: 'text',
success: async (res) => {
let result = await wait(res)
return result},
fail: function(res) {},
complete: function(res) {},
})
return await result
}
我也遇到了,改成下面这样 写就可以返回result了,你试试你的
const options = {
method: 'GET',
url: 'xxx',
json: true
};
return new Promise((resolve,reject)=>{
request(options, function (err, res, body) {
try{
resolve(body)
}catch(err){
reject(err)
}
})
})
异步的原因,request改成同步后就可以了。
这里用到了同步的request的用法,仅供参考:
https://developers.weixin.qq.com/community/develop/doc/00048279e2c5f07923b71efaf51804