从promise内部的函数返回一个值

时间:2019-10-08 21:10:47

标签: node.js asynchronous promise

我正在尝试从promise中从函数csData()返回数组shiftInfo。

function crewsense(){

    var request = CS.find({}); 
    request
    .then(result => {
        var created = result[0].created,
            currentTime = moment(),
            diff = (currentTime - created);
        if(diff < 84600000){
            console.log("Current Token is Valid");
            var access_token = result[0].access_token;
            console.log('Obtaining Crewsense Shift Data');
            return access_token
        }else{
            console.log("Current Token is invalid. Updating Token");
            csToken();
        }
    }).then(access_token => {
        csData(access_token) //I am trying to get this function to return async data.

    }).then(shiftInfo => { //I want to use the data here.

})

这是csData函数:

function csData(csKey) {
    const dayURL = {    
        method: 'get',
        url: 'https://api.crewsense.com/v1/schedule?start='+today+'%2007:30:00&end='+tomorrow+'%2007:30:00',
        headers:{
            Authorization: csKey,
            }
        }

    const request = axios(dayURL)

    request
    .then(result => {
        var shiftInfo = [];
        var thisShift = [];
        var onDuty = result.data.days[moment().format("YYYY-MM-DD")].assignments;
        thisShift.push(result.data.days[moment().format("YYYY-MM-DD")].day_color);
        var persons = [];

        var i = 0;
        for(var i=0; i<onDuty.length; i++){
            let station = onDuty[i].name    
            for(var x=0; x<onDuty[i].shifts.length; x++){
                var person = {
                    name: onDuty[i].shifts[x].user.name,
                    position: onDuty[i].shifts[x].qualifiers[0].name,
                    station: station
                }
            persons.push(person);   
            }   
        }
        shiftInfo = [{thisShift}, {persons}];
        // console.log(shiftInfo)
        return shiftInfo
    })
    .catch(error => console.error('csData error:', error))
}

我尝试分配不成功的var shiftInfo = csData(access_token)和其他几种调用csData函数的方法。我试图在这里阅读其他类似的问题,但我最终感到困惑。如果有人可以向我指出正确的方向,或者请指出解决方法,我也许可以将其单击在我的脑海中。

我感谢每个人的时间。

谢谢!

1 个答案:

答案 0 :(得分:1)

return内的任何then都将传递给下一个then回调。如果您return Promise,则承诺的结果将发送到下一个then回调:

new Promise((resolve) => {
  // We resolve to the value we want
  resolve("yay");
}).then((value) => {
  // In the first then, value will be "yay"
  console.log("First then:", value);
  // Then we return a new value "yay x2"
  return value + " x2";
}).then((value) => {
  // In this second then, we received "yay x2"
  console.log("Second then:", value);
  // Then we return a promise that will resolve to "yay x2 again"
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(value + " again");
    }, 1000);
  });
}).then((value) => {
  // After a second (when the returned Promise is resolved) we get the new value "yay x2 again"
  console.log("Third then:", value);
  // And now we return a Promise that will reject
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(new Error("wtf"));
    }, 1000);
  });
}).catch((error) => {
  // This catch on the whole promise chain will catch any promise rejected
  console.log(error.toString());
});

因此,csData必须返回创建的诺言,而您需要将该诺言返回给您想要的then回调:

[...]
}).then(access_token => {
    return csData(access_token) //I am trying to get this function to return async data.
}).then(shiftInfo => { //I want to use the data here.
    console.log(shiftInfo);
}).catch((err) => {
    // Whatever...
});

function csData(csKey) {
    [...]
    return request.then(result => {
    [...]
}

由于您要返回承诺,因此建议您在catch外部添加csData并将其添加到以前的承诺链中。