请问函数调用时,由于异步问题不能获取值,该怎么处理呢?
发布于 7 年前 作者 xiulan69 9470 次浏览 来自 官方Issues

各位前辈,现在需要在页面里去调用外部函数,来获取云开发数据库里的数据,但返回值总是undefined,该怎么处理呢?程序附在后面。

调用的函数里console是有值的,但在page里返回值总是undefined。在同一页面里会用 promise 来写,这种不在同一页面的调用不知该咋搞了?拜托赐教。

////////////////page///////////

var getPrice = require("…/…/…/rsc/js/get_price.js");

Page({

let test = getPrice.test(record_id, ‘2019-12-10’);

console.log(“函数调用回传值,test::”, test);    //这里打印出来值是 undefined,还没等调用的函数去到值,这里就先给出了结果,咋搞?

})

////////////////外部函数///////////

const db = wx.cloud.database()

const test = (record_id, date) => {

var result = {};

db.collection(‘host_info’).where({ //查询是否有记录

_id: record_id,

‘weekend_set.chosen_dates’: date

}).count().then(res => {

if (res.total > 0) //如果查到符合要求的条目,则获取下面数据并返回值

{

db.collection(‘host_info’).where({

_id: record_id,

})

.get().then(res1 => {

result = res1.data[0].weekend_set;

})

return result;

} else   //如果没查到符合要求的条目,则获取下面数据并返回值

{

db.collection(‘host_info’).where({

_id: hotel_id,

})

.get().then(res2 => {

result = res2.data[0].normal_set;

})

return result;

}

})

}

module.exports = { test: test,}

3 回复

const test = async (record_id, date) => {

    var result = {},res,res1,res2

    res = await db.collection(‘host_info’).where({

        _id: record_id,

        ‘weekend_set.chosen_dates’: date

    }).count()

    if(res.total > 0){

        res1 = await db.collection(‘host_info’).where({

        _id: record_id,

        }).get()

        result = res1.data[0].weekend_set;

    } else {

        res2 = await db.collection(‘host_info’).where({

        _id: hotel_id,

        }).get()

        result = res2.data[0].normal_set

    }

    return result

}

const test = (record_id, date) => {
  return new Promise(function(resolve,reject)){
     ......
    resolve(result);
  }
}
getPrice.test(record_id, '2019-12-10').then(function(result){
  let test = result
})


不要勾es6转es5,基础库选高版本的,不用勾增强编译,可以直接用async/await.

回到顶部